Want a const array...

  • Thread starter Thread starter Sinex
  • Start date Start date
S

Sinex

Hi,
I want to declare an array of constants (of type byte) and initialize the
array ...all at one shot. How do I do that?

Sinex
 
Sinex,

There is no such thing as an "array of constants". A normal array
contains values that can be changed.

To define a normal array and assign it values, use the syntax:

byte[] myArray = {1, 2, 3, 100, 205, etc.}

Best Regards
Johann Blake
 
Afaik there is no direct way how to do this
you can declare for expample

public readonly byte[] arr = new byte[3] { 0x01, 0x02, 0x03 };

However, array elements aren't readonly.

Another way is to use ArrauyList

private static byte[] arr = new byte[3] { 0x01, 0x02, 0x03 };
public readonly ArrayList al = ArrayList.ReadOnly(ArrayList.Adapter(arr));

al is readonly collection. The minus of such a collection is that if you
will try to set the value of it you will get runtime exception and not the
error in the compile-time
 
Sinex said:
I want to declare an array of constants (of type byte) and
initialize the array ...all at one shot. How do I do that?

As mentioned, there's no convenient built-in way to do this, but what you
can do is declare a simple class that wraps an array and only exposes the
ability to read it, like this (warning, code is untested):

class ConstArray {
byte[] data;

public ConstArray(byte[] data) {
this.data = data;
}

public byte this [int index] {
get
{
return data[index];
}
}
}

Now you can declare in your class:

public readonly ConstArray arr = new ConstArray(new byte[3] {0x01, 0x02,
0x03});

Now the compiler will enforce that neither the array nor its elements can be
changed. If possible you may want to make ConstArray a value type to avoid
unneccessary indirection.
 
Back
Top