Const Arrays ?

  • Thread starter Thread starter Stu Banter
  • Start date Start date
S

Stu Banter

I have an array filled with const Int32, right now it is defined just as a
public variable with an initializer.

// as it is now
public int [] myarr = new int [] {1,2,3,4,5}

// as it should be logically but doesn't work.
public const int [] myarr = new int [] {1,2,3,4,5}

If that is not possible, I considered making it a private var with a get
accessor only, but how do I make one for an array or one of its elements ?

Thanks for your replies

Stu
 
Stu,
// as it should be logically but doesn't work.
public const int [] myarr = new int [] {1,2,3,4,5}

You can do

public static readonly int [] myarr = new int [] {1,2,3,4,5};

That makes the array reference read-only, but does not prevent someone
from changing the array content.



Mattias
 
You could encapsulate the array in a class to protect the array elements:

class ReadOnlyIntArray
{
private int[] array;

public ReadOnlyIntArray(int[] array)
{
this.array = array;
}

public int this[int index]
{
get { return array[index]; }
}
}

class MyApp
{
static void Main()
{
ReadOnlyIntArray myarr = new ReadOnlyIntArray(new int[] {1, 2, 3, 4,
5});
int x = myarr[3]; // ok
myarr[3] = 42; // won't compile
}
}

In this example the array was allocated an initialized inside the
constructor call. If it had been done outside the call, e.g.

int[] temp = {1, 2, 3, 4, 5};
ReadOnlyIntArray myarr = new ReadOnlyIntArray(temp);

then changes to temp[] would modify the array contents. If you want to
prevent that, you could modify the constructor to say

this.array = (int[]) array.Clone();

to make a copy of the array instead of just copying the reference.


Mattias Sjögren said:
Stu,
// as it should be logically but doesn't work.
public const int [] myarr = new int [] {1,2,3,4,5}

You can do

public static readonly int [] myarr = new int [] {1,2,3,4,5};

That makes the array reference read-only, but does not prevent someone
from changing the array content.



Mattias
 
Back
Top