I just looked into IReadOnlyList<T>
to create readonly list. But I think it is not 100% readonly. I can not add/remove the item from the list but I can still modify the members.
Consider this example.
class Program
{
static void Main(string[] args)
{
List<Test> list = new List<Test>();
list.Add(new Test() { MyProperty = 10 });
list.Add(new Test() { MyProperty = 20 });
IReadOnlyList<Test> myImmutableObj = list.AsReadOnly();
// I can modify the property which is part of read only list
myImmutableObj[0].MyProperty = 30;
}
}
public class Test
{
public int MyProperty { get; set; }
}
To make it truly readonly I have to make MyProperty
as readonly. This is a custom class, it's possible to modify the class. What if my list is of inbuilt .net class which has both getter & setter properties? I think in that case I have to write a wrapper of that .net class which only allows reading the value.
Is there any way to make the existing classes immutable?