why use 'new' in overriding?

  • Thread starter Thread starter Nilesh
  • Start date Start date
N

Nilesh

I am confused about the purpose of 'new' in overriding.
Consider following example.

<code_snippet>

using console = System.Console;
public class TestClass
{
public static void Main()
{
Base oBase = new Base();
oBase.test_call();

Derived oDerived = new Derived();
oDerived.test_call();


Base oDerived2 = new Derived();
oDerived2.test_call();

console.ReadLine();
}
}


class Base
{
public void test_call()
{
console.WriteLine("Base::test_call()");
}
}

class Derived : Base
{
public void test_call()
{
console.WriteLine("Derived::test_call()");
}
}


</code_snippet>

In the derived classes' test call method, what is the use of adding
new? i.e.

new public void test_call()

Both the cases produce same result. So what is the purpose of 'new'?
Am i missing something too obvious?

Thanks in advance
Nilesh Dhakras
 
In the derived classes' test call method, what is the use of adding
new? i.e.

new public void test_call()

Both the cases produce same result. So what is the purpose of 'new'?
Am i missing something too obvious?

new is meant to indicate that you know full well that you're hiding a
method instead of overriding it, and that it is indeed what you want to
do.

It's rarely the right thing to do, however - most of the time you
should be overriding or using a different name.
 
As Jon said, it's there to avoid confusion and help debugging your code.
It's not required, even though Visual Studio will mark the method and
claim "'new' is required" in the tooltip.
 
Hi,
the purpose of the new operator is to hide the base classes member with the
name you're using it on.
MSDN says:

Name hiding through inheritance takes one of the following forms:

a.. A constant, field, property, or type introduced in a class or struct
hides all base class members with the same name.
b.. A method introduced in a class or struct hides properties, fields, and
types, with the same name, in the base class. It also hides all base class
methods with the same signature. For more information, see 3.6 Signatures
and overloading.
 
Hi Nilesh
*new* doesn't change anything in your program it just tells the compiler
that you know what you are doing and the compiler won't report the warning
about hiding the base class method.

HTH
B\rgds
100
 
Back
Top