Alex Rivera | Logout

Are immutable arrays possible in .NET?

Asked 2008-10-16T21:49:16.340
29

Is it possible to somehow mark a System.Array as immutable. When put behind a public-get/private-set they can't be added to, since it requires re-allocation and re-assignment, but a consumer can still set any subscript they wish:

public class Immy
{
    public string[] { get; private set; }
}

I thought the readonly keyword might do the trick, but no such luck.

Edit
Report

2 Answers

8

You could use Array.AsReadOnly method to return.

answered 2008-10-16T21:57:03.907
2

I believe best practice is to use IList<> rather than arrays in public APIs for this exact reason. readonly will prevent a member variable from being set outside of the constructor, but as you discovered, won't prevent people from assigning elements in the array.

See Eric Lippert's article Arrays Considered Somewhat Harmful for more information.

Edit: Arrays can't be read only, but they can be converted to read-only IList implementations via Array.AsReadOnly() as @shahkalpesh points out.

answered 2008-10-16T21:52:33.917

Your Answer