This is all to do with polymorphism. When a virtual method is called on a reference, the actual type of the object that the reference refers to is used to decide which method implementation to use. When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class. For instance:
public class Base
{
public void Display()
{Console.WriteLine("Base Display");}
public virtual void SomeMethod()
{Console.WriteLine("virtual SomeMethod");}
public virtual void SomeOtherMethod()
{Console.WriteLine("virtual SomeOtherMethod");}
}
public class Derived : Base
{
public void Display()
{Console.WriteLine("Derived Display");}
public override void SomeMethod()
{Console.WriteLine("override SomeMethod");}
public new void SomeOtherMethod()
{Console.WriteLine("new SomeOtherMethod");}
}
will end up calling Derived.SomeMethod if that overrides Base.SomeMethod.Will first call Base.SomeOtherMethod , then Derived.SomeOtherMethod . They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the
base method.
If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).
base method.
If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).
static void Main(string[] args)
{
Base b1 = new Base();
b1.SomeMethod();
b1.Display();
Base b2 = new Derived();
b2.SomeMethod();
b2.Display();
Base b3 = new Derived();
b3.SomeOtherMethod();
Derived d = new Derived();
d.SomeOtherMethod();
}
Output
virtual SomeMethod
Base Display
override SomeMethod
Base Display
virtual SomeOtherMethod
new SomeOtherMethod
No comments:
Post a Comment