Re: Selecting appropriate override

Tech-Archive recommends: Speed Up your PC by fixing your registry



> 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
>
>


.



Relevant Pages

  • Re: Selecting appropriate override
    ... and I do not want to force adding a new override in the ancestor every time ... a new subclass is added. ... > But it's also an Ancestor, and that is the version it finds first. ... >> public static void Hello ...
    (microsoft.public.dotnet.languages.csharp)
  • Selecting appropriate override
    ... Ancestor dummy = new SubClass(); ... public static void Hello(SubClass pParm) ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Selecting appropriate override
    ... But it's also an Ancestor, and that is the version it finds first. ... Ancestor dummy = new SubClass(); ... > static void Main ... > public static void Hello(SubClass pParm) ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Selecting appropriate override
    ... If a particular overload is only applicable in the descendent, ... It doesn't have to be in the ancestor. ... > the compiler will recognize the object for the subclass it is and select ... > the appropriate override. ...
    (microsoft.public.dotnet.languages.csharp)