Reputation: 327
I have the following enumerator.
public enum Fruits
{
Banana = 1,
Apple = 2,
Blueberry = 3,
Orange = 4
}
And what I'd like to do is something like the following
static void FruitType(int Type)
{
string MyType = Enum.GetName(Fruits, Type);
}
Basically I want the string MyType to populate with the name corresponding to the integer I input. So if I enter 1, MyType should have a value of Banana.
Eg. FruitType(1) --> MyType = Banana
Upvotes: 1
Views: 178
Reputation: 69372
The first parameter of GetName requires the type.
static void FruitType(int Type)
{
string MyType = Enum.GetName(typeof(Fruits), Type);
}
If you're not planning on doing anything else in the method, you can return the string like this
static string FruitType(int Type)
{
return Enum.GetName(typeof(Fruits), Type);
}
string fruit = FruitType(100);
if(!String.IsNullOrEmpty(fruit))
Console.WriteLine(fruit);
else
Console.WriteLine("Fruit doesn't exist");
Upvotes: 7
Reputation: 223392
Basically I want the string MyType to populate with the name corresponding to the integer I input.
string str = ((Fruits)1).ToString();
You can modify your method like:
static string FruitType(int Type)
{
if (Enum.IsDefined(typeof(Fruits), Type))
{
return ((Fruits)Type).ToString();
}
else
{
return "Not defined";
}
}
The use it like
string str = FruitType(2);
Upvotes: 2