Reserved word "new" in interfaces c #

4

Greetings,

I've been playing with some AspNet identity stuff trying to undock some components.

When I try to define an interface that implements other interfaces (for this case, AspNet Identity interfaces) I get a warning in visual studio that tells me to use the reserved word "new" in each interface member because it is hiding a member of the interfaces that implements my interface.

Although the warning is effectively removed by adding to the beginning of each member's definition in the interface, I would like to know why this warning and the implications of using the "new" at the beginning of each member in the definition of the interface.

Thank you very much.

    
asked by Camilo Bernal 01.07.2016 в 18:41
source

1 answer

1

Correct me for not being right.

When you implement an interface in another, the word new is not that important unless you need to change something in that part.

You're basically saying "I want my new interface to be like the other one, but I want to change some things"

Example:

public interface IElement
{
    string Nombre { get; set; } 
}

public interface IAnotherElement : IElement
{
    new string Nombre { get; } 
}

The definition of IAnotherElement.Nombre will hide the direct behavior of IElement.Nombre , so you will only modify what happens. In the previous example, both definitions are valid, however, the warning is only a warning that tells you that can corrupt the behavior of the parent interface.

Using the previous example, if you hide a property, that element can not be inherited by classes that implement that property:

public class Element : IElement
{
    public string Nombre { get; set; } // Todo bien.
}

public class AnotherElement : IAnotherElement
{
    new public string Nombre { get; } // Warning.
}

Note the new in the implementation of the class.

But if we remove the new :

public class AnotherElement : IAnotherElement
{
    public string Nombre { get; } // Error de implementación.
}

The compiler warns you that the operator set is missing in the property definition.

I hope it has helped you, here I leave you a fiddle for you to see !!

    
answered by 01.07.2016 / 19:31
source