I have the following code in a public static class:
public static class MyList
{
public static readonly SortedList> CharList
The List have the AsReadOnly method that return a read only list should be what you want.
The readonly modifier just gaurantees that the variable 'CharList' cannot be re-assigned to something else from outside of the class constructor. You need to create your own dictionary structure that doesn't have a public Add() method.
class ImmutableSortedList<T, T1>
{
SortedList<T, T1> mSortedList;
public ImmutableSortedList(SortedList<T, T1> sortedList) // can only add here (immutable)
{
this.mSortedList = sortedList;
}
public implicit operator ImmutableSortedList<T, T1>(SortedList<T, T1> sortedList)
{
return new ImmutableSortedList<T, T1>(sortedList);
}
}
Or, if you truly can't change the implementation, make the SortedList private and add your own methods that control access to it:
class MyList
{
// private now
readonly SortedList<int, List<myObj>> CharList;
// public indexer
public List<myObj> this[int index]
{
get { return this.CharList[index]; }
}
}
The modifier readonly means that the value cannot be assigned except in the declaration or constructor. It does not mean that the assigned object becomes immutable.
If you want your object to be immutable, you must use a type that is immutable. The type ReadOnlyCollection<T> that you mentioned is an example of a immutable collection. See this related question for how to achieve the same for dictionaries: