tags:

views:

33

answers:

2

When using custom classes with read-only properties that are of type List or similar (ie, ObservableCollection), it is still possible to 'get' the variable and call an Add() method on it to alter the content.

Is there a way to stop this (without creating huge overloads of the List class) on 'external' access, or is it 'best practice' to handle lists in another way if they shouldn't be edited outside of their class?

+2  A: 

You should expose any such properties as type:

ReadOnlyCollection<T>

What is "read only" in the case of a read only reference property is just the reference to the object - it doesn't make the object immutable.

David M
+5  A: 

When you decalre a reference type as readonly, only the reference to the object is readonly. The object itself can still be modified. In the case of a List, you can use the ReadOnlyCollection to expose the collection so that it cannot be modified (and you can still use a List internally to store/modify the data.

FxCop actually has a rule to catch these situations:

Do not declare read only mutable reference types

private List<string> _internalList = new List<string>();

public ReadOnlyCollection<string> ListProperty
{
    get
    {
        return _inernalList.AsReadOnly();
    }
}

should do the trick.

Justin Niessner