I\'d like to have a class \"A\" with a (for example) SortedList collection \"SrtdLst\" property, and inside this class \"A\" allow the addition or subtraction of \"SrtdLst\" ite
EDIT: Original answer is below. As earwicker points out, I hadn't noticed that you aren't asking for it to be readonly - just to prevent the Add
operation. That doesn't sound like a good idea to me, as the only difference between Add
and the indexer-setter is that Add
throws an exception if the element is already present. That could easily be faked up by the caller anyway.
Why do you want to restrict just that one operation?
Original answer
For one thing, don't use public fields. That's a surefire way to run into problems.
It looks like you want a read-only wrapper class round an arbitrary IDictionary
. You can then have a public property which returns the wrapper, while you access the private variable from within your class. For example:
class A
{
private SortedList sortedList = new SortedList();
public IDictionary SortedList
{
get { return new ReadOnlyDictionaryWrapper(sortedList);
}
public A()
{
sortedList.Add("KeyA", "ValueA");
sortedList["KeyA"] = "ValueAAA";
}
}
Now you've just got to find a ReadOnlyDictionary
implementation... I can't implement it right now, but I'll be back later if necessary...