44

This is my enum:

public enum DocumentTypes
    {
        [EnumMember]
        TYPE_1 = 1,
        [EnumMember]
        TYPE_2 = 2,
        [EnumMember]
        TYPE_3 = 3,
        [EnumMember]
        TYPE_4 = 4,
        [EnumMember]
        TYPE_5 = 5,
        [EnumMember]
        TYPE_6 = 6,
        [EnumMember]
        TYPE_7 = 7,
        [EnumMember]
        TYPE_8 = 12

    }

If I want to obtain 'TYPE_8', if I only have 12, is there a way to get the enum value?

I tried this:

((DocumentTypes[])(Enum.GetValues(typeof(DocumentTypes))))[Convert.ToInt32("3")].ToString()

which returns a value of 'TYPE_4'

denny
  • 1,481
  • 1
  • 17
  • 26
ltech
  • 445
  • 1
  • 4
  • 5
  • fyi : http://stackoverflow.com/questions/1851567/chow-to-use-enum-for-storing-string-constants/1851601#1851601 http://stackoverflow.com/questions/630803/enum-with-strings – BillW Dec 17 '09 at 20:03

5 Answers5

70

You can directly cast it:

int value = 12;
DocumentTypes dt = (DocumentTypes)value;
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
38
string str = "";
int value = 12;
if (Enum.IsDefined(typeof (DocumentTypes),value))
     str =  ((DocumentTypes) value).ToString();
else
     str = "Invalid Value";

This gives will also handle invalid values trying to be used, without the internal exception being thrown

You can also replace the string with DocumentTypes, ie

DocumentTypes dt = DocumentTypes.Invalid; // Create an invalid enum
if (Enum.IsDefined(typeof (DocumentTypes),value))
   dt = (DocumentTypes) value;

And for the bonus point, here is how to add a custom string to an enum (copied from this SO answer)

Enum DocumentType
{ 
    [Description("My Document Type 1")]
    Type1 = 1,
    etc...
}

Then add an extenstion method somewhere

public static string GetDescription<T>(this object enumerationValue) where T : struct
{
    Type type = enumerationValue.GetType();
    if (!type.IsEnum)
        throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");

    //Tries to find a DescriptionAttribute for a potential friendly name
    //for the enum
    MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
    if (memberInfo != null && memberInfo.Length > 0)
    {
        object[] attrs = memberInfo[0].GetCustomAttributes(typeof (DescriptionAttribute), false);

        if (attrs != null && attrs.Length > 0)
        {
            //Pull out the description value
            return ( (DescriptionAttribute) attrs[0] ).Description;
        }
    }
    //If we have no description attribute, just return the ToString of the enum
    return enumerationValue.ToString();
}

Then you can use:

DocumentType dt = DocumentType.Type1;
string str = dt.GetDescription<DocumentType>();

Which will retrive the Description attribute value.


Edit - updated code

Here is a new version of the extension method that does't need to know the type of the Enum before hand.

public static string GetDescription(this Enum value)
{
    var type = value.GetType();

    var memInfo = type.GetMember(value.ToString());

    if (memInfo.Length > 0)
    {
        var attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attrs.Length > 0)
            return ((DescriptionAttribute)attrs[0]).Description;
    }

    return value.ToString();
}
AGuyCalledGerald
  • 7,882
  • 17
  • 73
  • 120
PostMan
  • 6,899
  • 1
  • 43
  • 51
7

First of all cast to your enum type and call ToString():

string str = ((DocumentTypes)12).ToString();
GraemeF
  • 11,327
  • 5
  • 52
  • 76
0

Try this:

    public enum EnumTest
    {
        EnumOne,
        EnumTwo,
        EnumThree,
        Unknown
    };
    public class EnumTestingClass{
        [STAThread]
        static void Main()
        {
            EnumTest tstEnum = EnumTest.Unknown;
            object objTestEnum;
            objTestEnum = Enum.Parse(tstEnum.GetType(), "EnumThree");
            if (objTestEnum is EnumTest)
            {
                EnumTest newTestEnum = (EnumTest)objTestEnum;
                Console.WriteLine("newTestEnum = {0}", newTestEnum.ToString());
            }
        }
    }

Now from the sample code you will see that newTestEnum will have the value from the 'EnumTest' equivalent of the string "EnumThree".

Hope this helps, Best regards, Tom.

t0mm13b
  • 34,087
  • 8
  • 78
  • 110
0
        public enum Projects
    {
        Hotels = 1,
        Homes = 2,
        Hotel_Home = 3
    }


int projectId = rRoom.GetBy(x => x.RoomId == room.RoomId).FirstOrDefault().ProjectId.TryToInt32();
Projects Project = (Projects)projectId;
Ata Hoseini
  • 117
  • 1
  • 4
  • 1
    While this code may provide a solution to the OP's question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained. – borchvm Feb 10 '20 at 07:24
  • so at first, you define your Enum set, and then use it on your code! – Ata Hoseini Apr 25 '20 at 07:07