0

I have an int and I want to know the corresponding enum value.

Actually have an enum and I want to return the corresponding value for another enum.

I might just use a large switch but I would like to know if there is a better way.

2
  • This easily could have been answered by reading the MSDN article on enumerations. The default value of an enumeration is an integer as LB points out all you need to do is cast it into an integer. Commented Sep 12, 2012 at 17:38
  • @Ramhound I can tell from the article ( msdn.microsoft.com/en-us/library/sbbt4032(v=vs.71).aspx ) that I can cast from enum to int, but it's not obvious to me I can go the other way around. Commented Sep 12, 2012 at 17:42

3 Answers 3

5

Something like this?

 MyEnum m = (MyEnum)((int)otherEnum);


  var en = (StringSplitOptions)SeekOrigin.Begin;
Sign up to request clarification or add additional context in comments.

Comments

5

How do the two enum types "correspond"? If there is no direct link, then yes, a large switch statement will be necessary. Otherwise, if they have the same underlying value, then you can simply cast from one type to the other. If you have an int, you can also cast that to the desired enum type.

Comments

1

There are two cases, one where the enums are sharing the values, and one when they are sharing the name. You can cast the values and parse the names as shown here. If neither the names nor the values are the same you of course can't do this.

public void Test() {
    var one = FirstEnumWithSameValues.Two;
    var two = (SecondEnumWithSameValues) one;

    var three = FirstEnumWithSameName.Two.ToString();
    var four = (SecondEnumWithSameName) Enum.Parse(typeof(SecondEnumWithSameName), three);
}

public enum FirstEnumWithSameValues
{
   One = 1,
   Two = 2,
   Three = 3
}

public enum SecondEnumWithSameValues
{
    Uno = 1,
    Due = 2,
    Trez = 3
}

public enum FirstEnumWithSameName
{
    One = 1,
    Two = 2,
    Three = 3
}

public enum SecondEnumWithSameName
{
    One = 4,
    Two = 5,
    Three = 6
}

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.