Christian Fosli
Christian Fosli

Reputation: 1857

Why can't I use my enum type inside a switch expression?

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

Answers (1)

MistyK
MistyK

Reputation: 6232

As stated in my comment - Case value should be known at compile time.

Upvotes: 1

Related Questions