Question

Bit of a noobie question but hey ho.

Example:

BaseClass bc = new ExtendedClass(); //Assume ExtendedClass inherits from BaseClass
((BaseClass)bc).ExtendedMethod();
bc.ExtendedMethod();
((ExtendedClass)bc).ExtendedMethod(); //overridden in ExtendedClass

ExtendedClass ec = new ExtendedClass();
((BaseClass)ec).ExtendedMethod();
ec.ExtendedMethod();
((ExtendedClass)ec).ExtendedMethod(); //overridden in ExtendedClass 

?

What implementations will bc.ExtendedMethod(); and ec.ExtendedMethod(); call at runtime? Will they be different? I assume the casted calls will call the specific implementation within the class.

edit: added relevant tag.

Était-ce utile?

La solution

public class Base
{
    public void Extends()
    {
        Console.WriteLine("Base class");
    }
}

public class Extend : Base
{
    public new void Extends()
    {
        Console.WriteLine("Extend class");
    }
}


public class Program
{
    public static void Main()
    {

        Base b = new Base();
        b.Extends();

        Extend e = new Extend();
        e.Extends();

        Base be = new Extend();
        be.Extends();

        Console.Read();

   }

}

Results in the following output:

Base class
Extend class
Base class

Note you can also use the new keyword in the Extend class to hide the base Extends function.

public new void Extends() 
{

}

Autres conseils

In all three cases the overridden implementation of ExtendedMethod will be called, as you are creating an instance of ExtendedClass. After all, this is what polymorphism is all about.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top