Declaring a const array

  • Thread starter Thread starter Edward Diener
  • Start date Start date
E

Edward Diener

If I write:

int[] x = { 1 };

that is fine with the compiler, but if I try to declare the array as const,
meaning that it will not be changed:

const int[] x = { 1 };

I receive the error message:
error CS0623: Array initializers can only be used in a variable or field
initializer. Try using a new expression instead.

So now I try:
const int[] x = new int[1] { 1 };

and I get:
error CS0133: The expression being assigned to
'Sis.Messaging.BasicSendersReceivers.TestTcpHandler.itest' must be constant
 
Arrays are probably one of those things that can only be evaluated at
runtime. Constants must be evaluated at compile time. Try using "readonly"
instead of "const".
 
You can't declare complex constants in C#.

You can get most of the desired effect by declaring it readonly, but
even that has its limitations.
 
Back
Top