-4

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.

Izzy
  • 1,764
  • 1
  • 17
  • 31
  • 3
    Why don't you give it a shot yourself, setup a sample project with base and child class and see – Habib Apr 05 '13 at 10:18
  • It's just with methods that only appear within the extension require a cast to be usable from the extended base class object and I was actually seeing if I could snag the actual concept of this *ty alex* and actually have this somewhere useful so that every programmer doesn't have to test this to find out. – Izzy Apr 05 '13 at 10:31
  • 1
    Depends; is ExtendedMethod virtual? – It'sNotALie. Apr 05 '13 at 10:37
  • It's a question about a concept - so it could be. – Izzy Apr 05 '13 at 10:51

2 Answers2

2

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.

Alexander Tsvetkov
  • 1,649
  • 14
  • 24
2
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() 
{

}
Darren
  • 68,902
  • 24
  • 138
  • 144
  • 1
    Ahh ok - if you use virtual+override the last one is Extended; but if you use "new" the last is Base. – Izzy Apr 05 '13 at 10:42