Is the following not a good practice?
public interface IMyImmutableData
{
int Data { get;}
}
public interface IMyMutableData
{
int Data { set;get;}//implements both get and set
}
public class MyData : IMyImmutableData, IMyMutableData
{
public int Data{get;set;} //implements both IMyImmutableData, IMyMutableData
}
void Main()
{
MyData myData = new MyData{Data=10};
Console.WriteLine(myData.Data);
}
The reason I ask is that resharper gives me the following warning: “possible ambiguity while accessing by this interface”
The reason I want to do the above is that when I create methods that use the MyData class, I would like to send it either as IMyMutable or IMyImmutable objects, so that users of the method know that they can expect the method to update or not update the passed in object.
I think in this case your structure is fine. You don’t want to explicitly implement the interfaces via separate properties, because then the
Datayou access via the immutable interface will actually be different than that for the mutable interface.Also, your actual code is likely more complex, because in this case there is no ambiguity: you are accessing
Datavia the object itself, so interfaces need not be considered.One solution with explicit interface implementation would be to use a common backing field, rather than auto-properties: