Stopbyte

The use of "new" keyword C# in Property declaration

I’ve seen some C# tutorials that declare a Property using the new Keyword this way:

public new int ID {
    get {
        return _id;
    }
    set {
        _id = value;
        OnPropertyChanged("ID");
    }
}

What that “new” keyword is used for here?

as as far as i know the “new” keyword is only used to create an instance of an object!

2 Likes

The “new” modifier in C# can be used for class members (but it’s completely optional). It’s used to tel the compiler that the given C# property, method or member hides a similar member in the base class.

Lets assume this is a Base Class definition:

public class BaseClass
{
    public int SomeMember;
    public void SomeMethod() { }
}

And this one being the derived class of the base class above:

public class DerivedClass : BaseClass
{
    new public void SomeMethod() { }
}

So now when we create an instance of the Class DerivedClass and make a call to DerivedClass.SomeMethod() the new method will be called.

Thus we can say BaseClass.SomeMethod() is hidden by DerivedClass.SomeMethod().

For full description of how new modifier works in C# class members, limitations and rules, please take a look at this msdn Article: new Modifier (C# Reference).

Hope that helps.

2 Likes

Shortly, The new modifier is used to indicate that a given property or Method declaration shadows/overrides a previous declaration in the class inheritance tree.

If same exact property/method (aka same name & same arguments (if any)) is present in the inheritance tree of the class. when using the “new” modifier you are indicating to the compiler that the right method to be called is the “new” one rather than calling an inherited member.

2 Likes

Thanks guys, it seems clear now… thanks for your fast answers. :slight_smile:

Sometimes I just love Stopbyte :stuck_out_tongue:

1 Like