Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we use both virtual and new keyword in methods of c#?

Tags:

function

c#

can we use both virtual and new keyword in methods of c#?

like image 696
naveenkumar Avatar asked Jan 22 '23 11:01

naveenkumar


2 Answers

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!
like image 86
Justin Niessner Avatar answered Jan 23 '23 23:01

Justin Niessner


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.

like image 29
Brian R. Bondy Avatar answered Jan 24 '23 00:01

Brian R. Bondy