Question

Collection properties

public List<MapMarker> Markers { get; set; }
public List<UIReport > Reports { get; set; }
Was it helpful?

Solution

To prevents clients from assigning a brand new collection, use a private field (readonly if applicable) and a public get-only property.

private readonly IList<T> _items = new List<T>();
public IList<T> Items
{
    get { return _items; }
}

To prevent clients from assigning a brand new collection and modifying your collection, use IReadOnlyCollection<T>

public MyClass()
{
    List<T> list = //new list
    _items = new ReadOnlyCollection<T>(list);    
}

private readonly IReadOnlyCollection<T> _items;
public IReadOnlyCollection<T> Items
{
    get { return _items; }
}

Returning a list as an IEnumerable<T> is not a very reliable option. The client can simply downcast the enumerable back to a list, and mutate. You should wrap the mutable list in a ReadOnlyCollection<T>.

OTHER TIPS

If you want a readonly collection use the ReadOnlyCollection class

var coll = new ReadOnlyCollection<char>("myreadonlycollection".ToCharArray());

Something like this?

public List<MapMarker> Markers { get; private set; }
public List<UIReport > Reports { get; private set; }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top