I have a class named WhatClass that has List field in it. I need to be able to read-only this field, so I used a get property to expose it to other objects.
public class WhatClass
{
List<SomeOtherClass> _SomeOtherClassItems;
public List<SomeOtherClass> SomeOtherClassItems { get { return _SomeOtherClassItems; } }
}
However it turns out that any object can call
WhatClass.SomeOtherClassItems.Add(item);
How can I prevent this?
As others have said, you are looking for the
.AsReadOnly()extension method.However, you should store a reference to the collection instead of creating it during each property access:
This is to ensure that
x.Items == x.Itemsholds true, which could otherwise be very unexpected for API consumers.Exposing
ReadOnlyCollection<>communicates your intent of a read-only collection to consumers. Changes to_itemswill be reflected inItems.