Wondering what the difference is between the following:
Case 1: Base Class
public void DoIt();
Case 1: Inherited class
<
new
means respect your REFERENCE type(left-hand side of=
) , thereby running reference types's method. If redefined method doesn't havenew
keyword, it is behaved as it has. Moreover, it also known as non-polymorphic inheritance. That is, “I’m making a brand new method in the derived class that has absolutely nothing to do with any methods by the same name in the base class.” - by said Whitakeroverride
, which must be used withvirtual
keyword in its base class, means respect your OBJECT type(right-hand side of=
), thereby running method overriden in regardless of reference type. Moreover, it also known as polymorphic inheritance.
My way to bear in mind both keywords that they are opposite of each other.
override
: virtual
keyword must be defined to override the method. The method using override
keyword that regardless of reference type(reference of base class or derived class) if it is instantiated with base class, the method of base class runs. Otherwise, the method of derived class runs.
new
: if the keyword is used by a method, unlike override
keyword, the reference type is important. If it is instantiated with derived class and the reference type is base class, the method of base class runs. If it is instantiated with derived class and the reference type is derived class, the method of derived class runs. Namely, it is contrast of override
keyword. En passant, if you forget or omit to add new keyword to the method, the compiler behaves by default as new
keyword is used.
class A
{
public string Foo()
{
return "A";
}
public virtual string Test()
{
return "base test";
}
}
class B: A
{
public new string Foo()
{
return "B";
}
}
class C: B
{
public string Foo()
{
return "C";
}
public override string Test() {
return "derived test";
}
}
Call in main:
A AClass = new B();
Console.WriteLine(AClass.Foo());
B BClass = new B();
Console.WriteLine(BClass.Foo());
B BClassWithC = new C();
Console.WriteLine(BClassWithC.Foo());
Console.WriteLine(AClass.Test());
Console.WriteLine(BClassWithC.Test());
Output:
A
B
B
base test
derived test
New code example,
class X
{
protected internal /*virtual*/ void Method()
{
WriteLine("X");
}
}
class Y : X
{
protected internal /*override*/ void Method()
{
base.Method();
WriteLine("Y");
}
}
class Z : Y
{
protected internal /*override*/ void Method()
{
base.Method();
WriteLine("Z");
}
}
class Programxyz
{
private static void Main(string[] args)
{
X v = new Z();
//Y v = new Z();
//Z v = new Z();
v.Method();
}