Posted by: Cirilo Meggiolaro | 01/26/2009

Tip of the day #104 – new Modifier

The “new” keyword usage for instantiate an object I am sure that you know but what about the “new” used as a modifier?

The idea of the “new” modifier is to explicitly tell that a member of a class (or even a nested class) is hiding a member with the same signature from a parent class.

Let’s check the following classes:

public class Foo
{
    public void M() { }
}

public class Bar : Foo
{
    public void M() { }
}

When you try to compile this code, you’ll get a warning (not an error) from the C# compiler questioning if the use of an operation with the same signature is intentional or made by mistake:

‘Tip104.Bar.M()’ hides inherited member ‘Tip104.Foo.M()’. Use the new keyword if hiding was intended.

The new modifier must be used to document that you want to redefine inherited members and automatically hide those members and that you haven’t misspelled.

The code below shows the modified code:

public class Foo
{
    public void M() { }
}

public class Bar : Foo
{
    new public void M() { }
}

As the same way, you may use the new modifier to hide other members such as properties or even nested classes:

public class A
{
    public string P { get; set; }
    public class NestedClass { }
}

public class B : A
{
    /// Hides a property.
    new public string P { get; set; }

    /// Hides a nested class.
    new public class NestedClass { }
}

Advertisements

Responses

  1. I´d like to see more of these tips related to OO! Very cool!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: