Is it possible somehow to achieve this behavior in C#:
public interface IReadOnly
{
Data Value { get; }
}
internal interface IWritable : IReadOnly
{
Hans Passant gave a very good answer and I've come to a similar answer, but I think I may be able to do one better:
public interface IReadOnly : IWritable
{
new int MyValue { get; }
}
public interface IWritable
{
int MyValue { get; set; }
}
public class Implementation : IReadOnly
{
public int MyValue { get; private set; }
int IWritable.MyValue
{
set { MyValue = value; }
get { return MyValue; }
}
public static Implementation GetMyImplementation()
{
return ImplementationGateway.GetMyImplementation();
}
}
public class ImplementationGateway
where TImplementation : class, IWritable, new()
{
public static TImplementation GetMyImplementation()
{
return new TImplementation
{
MyValue = 1
};
}
}
public class Program
{
public Program()
{
Implementation myImplementation = Implementation.GetMyImplementation();
myImplementation.MyValue = 0; //This will and is supposed to fail
}
}
The difference between my and mr. Passant's solution, is that my IReadOnly inherits from my IWritable. As a result of this code, you can't set MyValue within the Program class, which may be how you want it to work. Retrieve and map the data in your Gateway class, but then have it as a read only value beyond that. With that, you have read/write separation.
As an added bonus, the only thing your DAL knows about your objects, is the interface they share as a manner of 'contract'.
Interface Defined Model.