Reputation: 1857
I've got an enum called Category
, but with a few special attributes for translating the Enum into another langauge.
public enum Category
{
[StringValue("Varm mat")]
HotFood,
[StringValue("Kald mat")]
ColdFood,
}
I'm trying to map from the string value to the enum using a switch expression,
but I get a compilation error: The type name 'HotFood' does not exist on the type 'Category'
(and similar for ColdFood).
The GetStringValue()
method is an extension method we wrote for getting the StringValue attribute of the Enum.
public static Category MapStringToCategory(string stringValue)
{
var thisOneWorks = Category.HotFood.GetStringValue(); // this debug line works fine
return stringValue switch
{
Category.HotFood.GetStringValue() => Category.HotFood, // error: 'HotFood' does not exist on the type 'Category'
Category.ColdFood.GetStringValue() => Category.ColdFood, // error: 'ColdFood' does not exist on the type 'Category'
_ => throw new InvalidOperationException($"No string value for {stringValue}")
};
}
I can't wrap my head around why Category.HotFood
works fine outside of switch expressions,
but not inside them.
I also tried with a regular switch statement, but same error.
Would appreciate some input.
I'm using C# 8 and .NET Core 3.1.
Upvotes: 0
Views: 331
Reputation: 6232
As stated in my comment - Case value should be known at compile time.
Upvotes: 1