Home > other >  Two interfaces have the same property name but different type how do you resolve it?
Two interfaces have the same property name but different type how do you resolve it?

Time:12-17

I have a class which implements two different interfaces from two different libraries. They both happen to have the same property name but they have different types.

How do I resolve this issue in my class?

This is the clash I have:

public class Connection : IGraphObject, IPathFind 
{
    Node _node; // Node implements both interfaces
    public INode NodeA => _node;       // comes from interface IGraphObject
    public IPathNode NodeA => _node;   // comes from interface IPathFind
}

I get an error

Already contains definition

which is no surprise. But how do I get around this?

CodePudding user response:

I don't think I explained myself very well in my comment above. An explicit implementation of an interface member is only accessible via a reference of the interface type. That means that, if you implement one or both of your same-named members explicitly, you can then add another member with a different name to expose the value from the explicit implementation. Here's a quick example:

class Program
{
    static void Main()
    {
        var data = new Data("Hello World", 100);

        Console.WriteLine(data.GetStringData());
        Console.WriteLine(data.GetIntegerData());
        Console.WriteLine(((IStringData)data).GetData());
        Console.WriteLine(((IIntegerData)data).GetData());
    }
}

public interface IStringData
{
    string GetData();
}

public interface IIntegerData
{
    int GetData();
}

public class Data : IStringData, IIntegerData
{
    private string stringData;
    private int integerData;

    public Data(string stringData, int integerData)
    {
        this.stringData = stringData;
        this.integerData = integerData;
    }

    public string GetStringData()
    {
        return ((IStringData)this).GetData();
    }

    public int GetIntegerData()
    {
        return ((IIntegerData)this).GetData();
    }

    string IStringData.GetData()
    {
        return stringData;
    }

    int IIntegerData.GetData()
    {
        return integerData;
    }
}

When using a reference of the class type, the interface members are inaccessible, so you access the data via the pass-through members. When accessing the same object via an interface reference, you can access the implemented member(s) of that interface specifically.

You can choose to implement only one of the interfaces explicitly if you want. I think that it would be appropriate to do it for both in most cases, but there may be some scenarios where doing it for one is more appropriate.

CodePudding user response:

You could keep the original property names and use explicit interfaces.

This would allow you to keep the original property names, but you would need to specify the interface name when accessing the properties.

  •  Tags:  
  • c#
  • Related