tags:

views:

102

answers:

4

Hi friends,

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

+7  A: 

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!
Justin Niessner
So, can we say that the "new" keyword in "B"s method says something like "Only use this implementation if the Instance is created of my specific type (B), and not of my parent type (A)? or is that just a coincidence...
funkymushroom
@funkymushroom no, it means 'only use this implementation if the code is working with my specific type'. Notice bAsA says 42!, but the instance is of type B / what's different is that it's being accessed as something of type A.
eglasius
+1  A: 

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.

Brian R. Bondy
+1  A: 

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() { }
}
Hans Passant
A: 

Yes , you can do it and child classes can override this virtual new method

saurabh