views:

389

answers:

3

Consider the following code:

public abstract class Test1
{
    public object Data { get; set; }
}

public abstract class Test2<T> : Test1
{
    public T Data { get; set; }
}

This will generate the following warning:

'Test2.Data' hides inherited member 'Test1.Data'. Use the new keyword if hiding was intended.

Why is this only a warning and what effect will adding the "new" keyword have?

According to my testing I cannot find any difference once the "new" keyword is added.

Don't get me wrong, I'm all for being explicit, but I was curious as to the benefit of adding "new".

My only thoughts on what it might be are:

  • Improved human readability
  • Some saving at run-time when the compiler isn't left to figure the inevitable out the long way around
+17  A: 

The only effect the new keyword has is to remove the warning. The purpose of getting the warning when not using the new keyword is to prevent from accidentally shadowing the method when you really meant to override it.

sepp2k
+1  A: 

Turn on report warnings as errors. This will force you to be more explicit with your usage of new and override.

DanDan
+1  A: 

new is used to hide a method or property of the base class. This is not like overriding it : the member doesn't need to have the same signature as the hidden base class member, and is not involved in polymorphism.

An example :

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

class B : A
{
    public new void Test()
    {
        Console.WriteLine("B.Test");
    }
}

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

public static void Main(string[] args)
{
    A aa = new A();
    aa.Test(); // Prints "A.Test"

    A ab = new B();
    ab.Test(); // Prints "A.Test" because B.Test doesn't overrides A.Test, it hides it

    A ac = new C();
    ac.Test(); // Prints "C.Test" because C.Test overrides A.Test

    B b = new B();
    b.Test(); // Prints "B.Test", because the actual type of b is known at compile to be B
}
Thomas Levesque
new does nothing (except suppressing a warning). The hiding happens by leaving out override.
Henk Holterman
Yes, but by specifying the `new` keyword, you explicitly hide the member. Although it doesn't change anything in the end, it proves that you know what you're doing, and didn't accidentally forgot the `override` keyword
Thomas Levesque
No, hiding also happens w/o new
Henk Holterman
I never said it didn't... I'm just saying that by using the `new` keyword, you *explicitly* hide the member, so there is not ambiguity on your intentions
Thomas Levesque