"new" keyword in property declaration in c#

C#.Netasp.net

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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).

Solution 2 - C#

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.

Solution 3 - C#

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.

Solution 4 - C#

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.

Solution 5 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBen RoweView Question on Stackoverflow
Solution 1 - C#RustyView Answer on Stackoverflow
Solution 2 - C#anishMarokeyView Answer on Stackoverflow
Solution 3 - C#SanthoshView Answer on Stackoverflow
Solution 4 - C#KMånView Answer on Stackoverflow
Solution 5 - C#NlinscottView Answer on Stackoverflow