I'm using a class
like an enum
because my entries need a custom string representation:
using System.Collections.Generic;
namespace MyProject
{
internal class Food
{
private string _value = "";
private Food(string value)
{
_value = value;
}
public override string ToString()
{
return _value;
}
internal static Food RedApple = new Food("red_apple");
internal static Food YellowBanana = new Food("yellow_banana");
internal static Food GreenMango = new Food("green_mango");
}
}
I can use the static
fields like Food.RedApple
just fine:
if (str == Food.RedApple.ToString())
Console.WriteLine("apple");
else if (str == Food.YellowBanana.ToString())
Console.WriteLine("banana");
else if (str == Food.GreenMango.ToString())
Console.WriteLine("mango");
else
Console.WriteLine("unknown");
However, when I use them inside switch
statements like so:
using System;
namespace MyProject
{
class Program
{
static void Main(string[] args)
{
string str = "red_apple";
switch (str)
{
case Food.RedApple.ToString():
Console.WriteLine("apple");
break;
case Food.YellowBanana.ToString():
Console.WriteLine("banana");
break;
case Food.GreenMango.ToString():
Console.WriteLine("mango");
break;
default:
Console.WriteLine("unknown");
break;
}
}
}
}
I get the following error:
The type name
RedApple
does not exist in the typeFood
[MyProject]
What exactly is going on here, and does this mean that I can't use my class inside switch
statements?