Reputation: 55
How can I effective extend enum to have more than 2 options. I am reading events from a file, line-by-line. I have a constructor
public enum EventType
{ A,D }
public class Event
{
public EventType Type { get; set; }
}
I assigned Type property like this:
Type = tokens[2].Equals("A") ? EventType.A : EventType.D,
where token[2]
is the string that holds values like "A".
This works fine when there are only A
and D
, but I want to have 2 more types; say R
and C
. When I add them to enum field, how can I get the type? The above is giving compilation errors as if using Type as a variable.
I appreciate your immediate help! Thanks
Upvotes: 0
Views: 5255
Reputation: 919
You may use Enum.Parse
to parse a string. For error handling you may use Enum.GetNames(typeof(EventType))
and iterate over the returned string array, which contains all possible names of the enum.
var type = (EventType)Enum.Parse(typeof(EventType), tokens[2]);
Upvotes: 0
Reputation: 437376
There are really only three sensible ways to go about this:
If the tokens will always correspond exactly to your enum members, you can use Enum.TryParse
:
EventType type;
if (Enum.TryParse(tokens[2], out type)) {
Type = type;
}
else { /* token does not exist as an enum member */ }
This approach is the simplest, but it's probably slower than the next one and it also has another drawback: the author of the code that provides tokens[2]
and the author of the enum must always keep their code in sync.
var dict = new Dictionary<string, EventType>
{
{ "A", EventType.A },
{ "D", EventType.D },
// more items here
}
Type = dict[tokens[2]]; // no error checking, please add some
This requires some setup, but it's probably the fastest and it also allows accounting for changes in the input strings and/or enum values.
Alternatively, you can annotate your enum members with a custom attribute and write a helper method that uses reflection to find the correct member based on the value of this attribute. This solution has its uses but it's the least likely candidate; most of the time you should prefer one of the two alternatives.
Upvotes: 5
Reputation: 39610
You can want to use Enum.Parse
to get the matching value:
Type = Enum.Parse(typeof(EventType), tokens[2])
If tokens[2]
is not defined in EventType
, Enum.Parse
throws an exception, so you can use Enum.IsDefined
to check if there is an enum value for the string:
Enum.IsDefined(typeof(EventType), tokens[2])
Upvotes: 0
Reputation: 1235
EventType et;
switch(tokens[2])
{
case "A":
et=EventType.A;
break;
case "B":
et=EventType.B;
break;
case "C":
et=EventType.C;
break;
}
return et;
Upvotes: -2