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 ..

Mickaël Derriey
  • 12,796
  • 1
  • 53
  • 57
vmb
  • 2,878
  • 15
  • 60
  • 90

2 Answers2

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
    }
}
Mickaël Derriey
  • 12,796
  • 1
  • 53
  • 57
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");
    }
}
codersl
  • 2,222
  • 4
  • 30
  • 33
  • the `Enum.Parse` function will throw an exception is the value `colorName` can't be parsed into a `Colors`. – Mickaël Derriey Feb 15 '17 at 01:11
  • after googling,using same approach we can use Enum.TryParse..right?? – vmb Feb 15 '17 at 01:13
  • 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ël Derriey Feb 15 '17 at 01:16
  • @MickaëlDerriey good point... I've updated to use try/catch block as an alternative or you can use Enum.TryParse(). – codersl Feb 15 '17 at 01:20