Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are immutable arrays possible in .NET?

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.

like image 681
Neil C. Obremski Avatar asked Oct 16 '08 21:10

Neil C. Obremski


People also ask

Is array immutable in C#?

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.

Are arrays immutable?

Mutable is a type of variable that can be changed. In JavaScript, only objects and arrays are mutable, not primitive values.

What are immutable types in C#?

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.

How do you make an array immutable?

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.


2 Answers

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.

like image 143
Quantenmechaniker Avatar answered Sep 24 '22 23:09

Quantenmechaniker


ReadOnlyCollection<T> is probably what you are looking for. It doesn't have an Add() method.

like image 27
Ray Jezek Avatar answered Sep 22 '22 23:09

Ray Jezek