1

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

3
  • On of the reasons this is not normally done is that the strings obtained this way are hard to localize. Just an fyi. I'll have an answer in a minute after I dig up some old code that demonstrates this. Commented Jul 29, 2013 at 14:51
  • Also, a better FruitType function design would return a string Commented Jul 29, 2013 at 14:51
  • Okay, others beat me to it :) Commented Jul 29, 2013 at 14:57

2 Answers 2

7

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");
Sign up to request clarification or add additional context in comments.

7 Comments

Convert.ToString doesn't ensure null.
If you want to avoid null you could do Enum.GetName(typeof(Fruits), Type) ?? string.Empty
@SriramSakthivel - Sorry, I'm not following. I said it ensures that a NullReferenceException isn't thrown, not that it ensures null. Enum.GetName returns null if the enum value can't be found. If you call ToString on that, it will throw an exception. By using Convert.ToString instead, it will return null.
Without Convert.ToString will a NullReferenceException be thrown?
@user2094139 - Yup. It was fine before, it just had an extra call that wasn't necessary (forgot a string was being returned anyway from the GetName call).
|
2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.