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.
An array is not immutable, even if the elements it holds are immutable. So if an array slot holds a string, you can change it to a different string. This does not change any of the strings, it just changes the array.
Mutable is a type of variable that can be changed. In JavaScript, only objects and arrays are mutable, not primitive values.
An immutable type, in the context of C#, is a type of object whose data cannot be changed after its creation. An immutable type sets the property or state of the object as read only because it cannot be modified after it is assigned during initialization.
There is one way to make an immutable array in Java: final String[] IMMUTABLE = new String[0]; Arrays with 0 elements (obviously) cannot be mutated. This can actually come in handy if you are using the List.
The Framework Design Guidelines suggest returning a copy of the Array. That way, consumers can't change items from the array.
// bad code // could still do Path.InvalidPathChars[0] = 'A'; public sealed class Path { public static readonly char[] InvalidPathChars = { '\"', '<', '>', '|' }; }
these are better:
public static ReadOnlyCollection<char> GetInvalidPathChars(){ return Array.AsReadOnly(InvalidPathChars); } public static char[] GetInvalidPathChars(){ return (char[])InvalidPathChars.Clone(); }
The examples are straight from the book.
ReadOnlyCollection<T>
is probably what you are looking for. It doesn't have an Add()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With