Re: Selecting appropriate override
- From: "Adam Clauss" <cabadam@xxxxxxxx>
- Date: Tue, 30 Aug 2005 15:11:22 -0500
> In this peice of code, I would have expected 27 to print, but it always
> prints "Field1". It seems that it does not recognize that, although the
> parameter is declared as «Ancestor», it really is of «SubClass» class.
> Any suggestion here?
I'm pretty sure the decision for which Hello method should be used is
decided at compile time.
At compile time, all it knows about that variable is that it's declared type
is Ancestor. The assignment to it of "new SubClass" takes place at
runtime - the compiler has no way of predicting this.
Therefore, when the compiler sees a variable of Ancestor, it gives it to the
Hello method which takes a Ancestor as it's parameter.
Marina is right - this "Hello" method should be a virtual member of
ancestor, which SubClass can then change if it needs to. If a subclass of
ancestor does not need to change it, it can just leave it. This way you do
not have to keep adding methods to the Container class for each subclass of
Ancestor.
Ex:
public class Ancestor
{
public string Field1 = "Field1";
public virtual void DoHello()
{
Console.WriteLine(Field1);
}
}
public class SubClass : Ancestor
{
public int Field2 = 27;
public override void DoHello()
{
Console.WriteLine(Field2);
}
}
public class Container
{
public static void Hello(Ancestor pParm)
{
pParm.DoHello();
}
}
--
Adam Clauss
> Thank you
>
> Real
>
>
.
- References:
- Selecting appropriate override
- From: Réal Forté
- Selecting appropriate override
- Prev by Date: Re: Easy way to cast an array of strings to an array of objects?
- Next by Date: Re: Abusing C#
- Previous by thread: Re: Selecting appropriate override
- Next by thread: Re: Selecting appropriate override
- Index(es):
Relevant Pages
|