"new" keyword in property declaration in C #

I was given a .net project for support. I was just looking at the code, and I noticed this in the property declaration:

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

I was wondering what the new modifier does for a property?

+52
Sep 06 '10 at 5:19
source share
5 answers

It hides the navUrl property of the base class. See the new modifier . As mentioned in this MSDN record, you can access the "hidden" property with full names: BaseClass.navUrl . Abusing either can lead to serious confusion and possible insanity (i.e. broken code).

+47
Sep 06 '10 at 5:22
source share

new hides the property.

It could be like 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 hides the base class property.

+7
Sep 06 '10 at 5:22
source share

Shadowing is called several times or the method is hidden ; The method invoked depends on the type of link at the dial peer. It might help .

+3
Sep 06
source share

It is also documented here .

Fragment code 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. 
+3
Sep 06 '10 at 5:57
source share

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

Take a look at the first example here, this gives a pretty good idea of ​​how the new keyword can be used to mask base class variables

0
Jun 01 '15 at 12:12
source share



All Articles