Hi friends,
can we use both virtual and new keyword in methods of c#?
Hi friends,
can we use both virtual and new keyword in methods of c#?
Yes. You would be defining a method that hid a method of a parent and allowed children to override. The behavior might be a little strange though. Say you had the following classes:
public class A
{
public void DoSomething(){ Console.WriteLine("42!"); }
}
public class B : A
{
public virtual new void DoSomething(){ Console.WriteLine("Not 42!"); }
}
public class C : B
{
public override void DoSomething(){ Console.WriteLine("43!"); }
}
Then your execution would look something like:
A a = new A();
A bAsA = new B();
A cAsA = new C();
B b = new B();
B cAsB = new C();
C c = new C();
a.DoSomething(); // 42!
b.DoSomething(); // Not 42!
bAsA.DoSomething(); // 42!
c.DoSomething(); // 43!
cAsB.DoSomething(); // 43!
cAsA.DoSomething(); // 42!
Yes you can combine both.
virtual
allows a method to be overridden in a derived class
new
allows you to hide the old method.
Both are complementary and not contradicting.
Don't hesitate to just try this yourself, Visual Studio makes it easy.
class Base {
public virtual void Method() { }
}
class Derived : Base {
public virtual new void Method() { }
}
Yes , you can do it and child classes can override this virtual new method