I have a business entities as below,
class Class1
{
List<Class2> classes = new List<Class2>();
public IEnumerable<Class2> Classes { get { return classes.AsEnumrable(); }
public void AddClass(Class2 cls)
{
classes.Add(cls);
}
}
class Class2
{
public string Property { get; set; }
}
My business logic requires that once a Class2 instance is added using the AddClass method to the top of the Classes list in Class1, no one should be able to edit the properties of the Class2 instances added previously to the list, only the last item in the list could be edited. How do I do this?
I have tried IReadOnlyList, but it appears that it is concerned with making the list structure itself uneditable without preventing the edit of its items' content.
It's not a container's job to dictate the behavior of its items. A container is just that - an object that contains other objects. An
IReadOnlyListis a container whose items cannot be modified. But the items within it are jsutClass2instances - there's nothing that the container can do to prevent them from being edited.Consider this:
Should this be legal in your scenario? What's the difference between the two?
firstItemis simply an instance ofClass2that has no idea it was once inside a read-only collection.What you need is for
Class2itself to be immutable. That's up to the class, not the container. Read up on immutability, which is an important concept to grasp, and implementClass2accordingly. If you need a regular, mutableClass2to change its behavior, perhaps add aToImmutable()method to it which returns a different item, without a setter.