Reputation: 7074
I'm designing an application that requires a "location" field. The values for the location are "3241", "4112", "ND" and "TRAVEL", and I am trying to set up an enum
that includes those values.
I started with
enum projectLocation {3241,4112,ND,TRAVEL};
but the values 3241 and 4112 indicated a syntax error--identifier expected
--for the first value in the enum
. If I understand enum
correctly, that's because the above statement is looking for the value for the enum
's integer indeces of 3241
and 4112
. Is this a correct assumption?
I tried overriding that with the following
enum projectLocation {3241=0,4112,ND,TRAVEL};
and
enum projectLocation {3241=0,4112=1,ND=2,TRAVEL=3};
but I'm still getting the same syntax error on the 3241
value. Interestingly though, on both of these statements, there is NO syntax error on 4112, but I get can't find the namespace or name ND
and ...TRAVEL
It makes sense that enum
will not allow a mix of strings and integers, and I have two other enum
s that work fine and are only lists of string values, corroborating that theory. Is there a way to force enum
to accept the numeric values as strings? I've not been able to find any references in MSDNs C# documentation.
Upvotes: 3
Views: 1619
Reputation: 73502
Enums are called as named constants, so basically you give a name for some constant. Names are "identifiers" in c#, where identifier can contain numbers but first character cannot be a number.
You can add _
before that to fix this error.
enum projectLocation
{
_3241=0,
_4112=1,
ND=2,
TRAVEL=3
}
Also note the Fields, Properties Methods or whatever falls under this identifier rule mentioned above.
Upvotes: 6
Reputation: 56586
You can't do it exactly like you're trying to. Here's an alternative:
enum projectLocation {
L3241=3241,
L4112=4112,
ND=2,
TRAVEL=3
}
Starting them with a letter makes them valid enum identifiers, and setting their value equal to their number lets you do things like (projectLocation)3241
and get the expected L3241
value.
If you need the values to be 3241
and 4112
when serialized, include the proper attribute for your serialization approach, e.g. with Json.NET:
enum projectLocation {
[JsonProperty("3241")]
L3241=3241,
[JsonProperty("4112")]
L4112=4112,
ND=2,
TRAVEL=3
}
Upvotes: 5
Reputation: 10882
C# does not allow the first character of member names to start with a number. Consider using the @
character as a prefix, or some other character that conveys a meaning useful to a reader of the code as a number in isolation may not be very intuitive to a reader not familiar with the significance of 3241
in your context.
Upvotes: 1
Reputation: 117175
You would need to do something like this:
enum projectLocation { v3241, v4112, ND, TRAVEL };
or:
enum projectLocation { _3241, _4112, ND, TRAVEL };
My preference would be the use of the underscore.
Upvotes: 3