Declaring a const array

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
 
P

Peter Rilling

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".
 
B

Bruce Wood

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top