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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With