Best way to make a contained array's elements accessible but immutable outside containing class - C#
[ Best way to make a contained array's elements accessible but immutable outside containing class ]
If I have a class like this:
public class ArrayContainer
{
public int[] Array { get; private set; }
public int Value { get; private set; }
public ArrayContainer()
{
Array = new int[] { 1, 2, 3, 4, 5 };
Value = 10;
}
}
This assures that Value
will not be able to be changed outside the ArrayContainer
class, but individual Array
values will be able to be changed. What is the easiest workaround to this to assure that you can view values in Array
, but not change them?
Answer 1
You could expose it as a read-only collection by using Array.AsReadOnly
.
public ReadOnlyCollection<int> MyArray { get; private set; }
MyArray = Array.AsReadOnly(new int[] { 1, 2, 3, 4, 5 });
Answer 2
I'd say your best bet would be to define your own ImmutableArray
class, which implements an indexer that has no setter. The getter would delegate to the indexer of your Array
member, which would be passed as a constructor parameter. Make Array
private then, and expose an instance of your ImmutableArray
class.
Answer 3
There is the readonlycollection which you could create and pass out to users of this class.
Answer 4
Actually, there is a read-only wrapper for collections in the base class library. It's the ReadOnlyCollection<T>
.
http://msdn.microsoft.com/en-us/library/ms132474.aspx
If I remember correctly, the compiler complains if you try to access the set
accessor.