I have the following class:
class SampleClass
{
private ArrayList mMyList;
SampleClass()
{
// Initialize mMyList
}
public ArrayList MyList
{
get { return mMyList;}
}
}
I want users to be able to get mMyList which is why i exposed the "get" via a property however i don't want changes they make to the object (ie. MyList.Add(new Class());) to make its way back into my class.
I guess i can return a copy of the object but that may be slow and i'm looking for a way that will provide a compile-time error informing the user that they shouldn't expect to be able to modify the returned value from the Property.
Is this possible?
With an ArrayList you are fairly limited because there is no readonly non-generic collection class in the BCL. The quick and dirty solution is to return a type of IEnumerable.
public IEnumerable MyList
{
get { return mMyList;}
}
This won't actually prevent someone from casting to ArrayList but it won't allow edits by default either
You can return an effectively readonly list by calling ArrayList.ReadOnly. However it's return type is an ArrayList so the user would still be able to compile with .Add but it would produce a runtime error.