Differnce between virtual/override and new

J

Jazper Manto

hi
what is the difference between virtual / override and new? until now i only
knew the virtual / override thing.
thanx for hint.
Jazper

//--- new ----------------------------------------
public class MyBaseA
{
public void Invoke() {}
}
public class MyDerivedA : MyBaseA
{
new public void Invoke() {}
}

//---virtual / override -----------------------------
public class MyBaseB
{
public virtual void Invoke() {}
}
public class MyDerivedB : MyBaseB
{
public override void Invoke() {}
}
 
B

Bjorn Abelli

Jazper said:
what is the difference between virtual / override
and new? until now i only knew the virtual / override
thing.

As you say you already know the use of virtual/override, you know that it's
a construction that facilitates polymorhism.

The "new" construction isn't a "polymorph" thingy, as it only can be used to
*hide* a method implementation from the superclass, but *only* when the type
of the variable is of the subclass type (hence no polymorphism).

Based on your examples, I'll show the difference:

MyBaseA ma1 = new MyDerivedA();
MyDerivedA ma2 = new MyDerivedA();

ma1.Invoke(); // runs the method in the superclass
ma2.Invoke(); // runs the method in the subclass

MyBaseB mb1 = new MyDerivedB();
MyDerivedB mb2 = new MyDerivedB();

mb1.Invoke(); // runs the method in the subclass
mb2.Invoke(); // runs the method in the subclass

As you see, the virtual/override construction looks at what type the actual
instance is, while new only looks at what type the *variable* is.


Hope this made it clearer.

// Bjorn A

P.S. It's more common to put the "new" keyword after the visibility keyword,
such as:

public new void Invoke() {}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top