I\'m pretty confused between some concepts of OOP: virtual
, override
, new
and sealed override
. Can anyone explain the dif
public class Base
{
public virtual void SomeMethod()
{
Console.WriteLine("B");
}
}
public class Derived : Base
{
//Same method is written 3 times with different keywords to explain different behaviors.
//This one is Simple method
public void SomeMethod()
{
Console.WriteLine("D");
}
//This method has 'new' keyword
public new void SomeMethod()
{
Console.WriteLine("D");
}
//This method has 'override' keyword
public override void SomeMethod()
{
Console.WriteLine("D");
}
}
Now First thing First
Base b=new Base();
Derived d=new Derived();
b.SomeMethod(); //will always write B
d.SomeMethod(); //will always write D
Now the keywords are all about Polymorphism
Base b = new Derived();
virtual
in base class and override in Derived
will give D(Polymorphism).override
without virtual
in Base
will give error.virtual
will write 'B' with warning (because no polymorphism is done).new
before that simple method in Derived
.new
keyword is another story, it simply hides the warning that tells that the property with same name is there in base class.virtual
or new
both are same except
new modifier
new
and override
cannot be used before same method or property.
sealed
before any class or method lock it to be used in Derived class and it gives a compile time error.