1

I have one enum like below

public enum Colors
{
    red,
    blue,
    green,
    yellow
}

I want to use it switch case

public void ColorInfo(string colorName)
{
    switch (colorName)
    {
        // i need a checking like (colorname=="red")
        case Colors.red:
            Console.log("red color");
            break;
    }
}

I am getting following error

 Cannot implicitly convert type 'Color' to string

Can anyone help on this ..

1
  • Try switch ((Colors)Enum.Parse(typeof(Colors), colorName)) Commented Feb 15, 2017 at 0:58

2 Answers 2

6

Your best bet in my opinion is to try to parse the string value you get as an input as a Colors value, then you can do the switch based on the enum only. You can do so by using the Enum.TryParse<TEnum> function:

public void ColorInfo(string colorName)
{
    Colors tryParseResult;
    if (Enum.TryParse<Colors>(colorName, out tryParseResult))
    {
        // the string value could be parsed into a valid Colors value
        switch (tryParseResult)
        {
            // i need a checking like (colorname=="red")
            case Colors.red:
                Console.log("red color");
                break;
        }
    }
    else
    {
        // the string value you got is not a valid enum value
        // handle as needed
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

So verbose for such a trivial concept. Not one of my favourite things about csharp.
0

You can't compare an enum to a string as they are different types.

If you want to compare a string to an enum description, then you need to convert it a string first:

public void ColorInfo(string colorName)
{
    if (Colors.red.ToString() == colorName)
        Debug.Print("red color");
}

You can't use a switch statement to do the string conversion as each case must be a constant and Colors.red.ToString() is not.

An alternative is to convert the string to an enum first and then a switch statement to compare.

public void ColorInfo(string colorName)
{
    try
    {
        Colors color = (Colors)Enum.Parse(typeof(Colors), colorName);
        switch (color)
        {
            case Colors.red:
                Debug.Print("red color");
                break;
        }
    }
    catch(ArgumentException ex)
    {
        Debug.Print("Unknown color");
    }
}

4 Comments

the Enum.Parse function will throw an exception is the value colorName can't be parsed into a Colors.
after googling,using same approach we can use Enum.TryParse..right??
of course you can, that's what my answer uses. I just wanted to point out that using that code might result in an unexpected exception being thrown since it's not surrounded by a try/catch.
@MickaëlDerriey good point... I've updated to use try/catch block as an alternative or you can use Enum.TryParse().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.