1

I have a set of C# constants, for example:

LoanApplication.CONST_FIELD_NAME_DOB
LoanApplication.CONST_FIELD_NAME_EMPLOYMENTSTATUS

at a later time, I want to create an array that holds these constants.

I have tried:

const string [] Constants = 
{
    LoanApplication.CONST_FIELD_NAME_DOB,
    LoanApplication.CONST_FIELD_NAME_EMPLOYMENTSTATUS,
}

but I get the error:

a const field of a reference type can only be initialized with null

There are lots of questions that relate to this problem, but none where the array contains a list of existing constants.

Any ideas?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Alex
  • 3,730
  • 9
  • 43
  • 94

1 Answers1

3

Since an array is a reference type, it can only be set to a default of something that doesn't need the code to run, so null is the only option to assign the const to.

Instead of const, you could use static readonly here, which isn't entirely the same (it is evaluated at runtime instead of compile time), but will come the closest to what you want.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325