75

I've been given a .NET project to maintain. I was just browsing through the code and I noticed this on a property declaration:

public new string navUrl
{
  get 
  {
    return ...;
  }
  set
  {
    ...
  }
}

I was wondering what does the new modifier do to the property?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Ben Rowe
  • 28,406
  • 6
  • 55
  • 75

5 Answers5

68

It hides the navUrl property of the base class. See new Modifier. As mentioned in that MSDN entry, you can access the "hidden" property with fully qualified names: BaseClass.navUrl. Abuse of either can result in massive confusion and possible insanity (i.e. broken code).

John Washam
  • 4,073
  • 4
  • 32
  • 43
Rusty
  • 3,228
  • 19
  • 23
  • 19
    The `new` modifier does not cause this behavior, it only tells the compiler you did it intentionally so it won't show a warning message. – BornToCode Mar 25 '14 at 17:46
18

new is hiding the property.

It might be like this in your code:

class base1
{
    public virtual string navUrl
    {
        get;
        set;
    }
}

class derived : base1
{
    public new string navUrl
    {
        get;
        set;
    }
}

Here in the derived class, the navUrl property is hiding the base class property.

John Washam
  • 4,073
  • 4
  • 32
  • 43
anishMarokey
  • 11,279
  • 2
  • 34
  • 47
8

This is also documented here.

Code snippet from msdn.

public class BaseClass
{
    public void DoWork() { }
    public int WorkField;
    public int WorkProperty
    {
        get { return 0; }
    }
}

public class DerivedClass : BaseClass
{
    public new void DoWork() { }
    public new int WorkField;
    public new int WorkProperty
    {
        get { return 0; }
    }
}    

DerivedClass B = new DerivedClass();
B.WorkProperty;  // Calls the new property.

BaseClass A = (BaseClass)B;
A.WorkProperty;  // Calls the old property.
Santhosh
  • 6,547
  • 15
  • 56
  • 63
  • 3
    Your code snippet clarifies the hiding concept well, however the `new` modifier does not cause this behavior, it only tells the compiler you did it intentionally so it won't show a warning message. – BornToCode Mar 25 '14 at 17:45
  • 1
    Then what does cause this behavior? Usually A.WorkProperty would call the property of the derived class, since A references a derived object, regardless of the references type. – Squirrelkiller Sep 07 '16 at 09:20
3

Some times referred to as Shadowing or method hiding; The method called depends on the type of the reference at the point the call is made. This might help.

KMån
  • 9,896
  • 2
  • 31
  • 41
1

https://msdn.microsoft.com/en-us/library/435f1dw2.aspx

Look at the first example here, it gives a pretty good idea of how the new keyword can be used to mask base class variables

Nlinscott
  • 786
  • 7
  • 11