new and override

  • Thread starter Thread starter Josh Gilfillan
  • Start date Start date
J

Josh Gilfillan

hi, i'm a noob to c sharp and was wondering what the difference is
between new and override? obviously if override is used virtual must be
in the base class, but apart from that, whats the difference?

Thanks,

Josh
 
Hi,

new is a short for new slot, that is when you create a virtal method,
all the overrides are using the same slot in the vtable.

when you use new in a deriving class on a virtual method, you kind of
break the virtuality.

for example:
class A
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
object obj = new C();
((C)obj).Print();
((B)obj).Print();
((A)obj).Print();
Console.ReadLine();
/*
C
B
B
*/
}

public virtual void Print()
{
Console.WriteLine("A");
}
}

class B : A
{
public override void Print()
{
Console.WriteLine("B");
}
}

class C : B
{
public new void Print()
{
Console.WriteLine("C");
}
}

when you hold the instance as C, calling the Print will use the new
slot...
when holding the instance as A or B, calling the Print will use the
first slot and will follow the vtable up until B and start from
there...

Eyal.
 
yes, and also you can use new in order to change the access modifier of
a method.

so you can make a public method become protected or private.

example:

class A
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
object obj = new B();
((A)obj).Print(); // will work
((B)obj).Print(); // will not compile
}


public virtual void Print()
{
Console.WriteLine("A");
}
}

class B : A
{
private new void Print()
{
Console.WriteLine("B");
}
}

Eyal.
 
That won't work. I can just cast it to the base class and call the method.

A x = new B();
x.Print();

The real reason for the 'new' keyword is backwards compatibility.

Lets say I own class A and you own class B.
Your class B inherits from my class A. It has a print method, but mine does
not.

Six months later, I add a print method to my class A. You want to use the
new version of A, but want to keep using your version of print without
breaking mine. You add the 'new' keyword in your class, and thus any code
that was using your print will continue to do so. Unfortunately, any new
code that wants to use my print method has to cast the object to the base
type, but that is a small price for not breaking all your code.

You should never design code using the new keyword. Save it for situations
that you cannot control.
 
Back
Top