Selecting appropriate override



Hi,

I have a puzzling case here:
using System;

namespace TestOverrides

{

class Class1

{

[STAThread]

static void Main(string[] args)

{

Ancestor dummy = new SubClass();

Container.Hello(dummy);

}

}

class Ancestor

{

public String Field1 = "Field1";

}

class SubClass : Ancestor

{

public int Field2 = 27;

}

class Container

{

public static void Hello(SubClass pParm)

{

Console.WriteLine(pParm.Field2);

}

public static void Hello(Ancestor pParm)

{

Console.WriteLine(pParm.Field1);

}

}

}

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?

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)
  • 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
    ... At compile time, all it knows about that variable is that it's declared type ... Therefore, when the compiler sees a variable of Ancestor, it gives it to the ... which SubClass can then change if it needs to. ... public class SubClass: Ancestor ...
    (microsoft.public.dotnet.languages.csharp)
  • out Parameter And Base Class ?
    ... SubClass y = new SubClass; ... static void Test(out BaseClass y) ... public BaseClass() ...
    (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)