Home
Manage Your Code
Snippet: Generic conversion of int value to an Enum (C#)
Title: Generic conversion of int value to an Enum Language: C#
Description: This method takes an int value and converts it to the supplied enum type (if available). Views: 617
Author: Robert Taylor Date Added: 11/16/2006
Copy Code  
1/// <summary>
2/// Converts the int to enum.
3/// </summary>
4/// <typeparam name="E">The enum type</typeparam>
5/// <param name="id">The id.</param>
6/// <param name="throwException">if set to <c>true</c> [throw exception].</param>
7/// <returns>
8/// The enum value represented by the supplied integer
9/// </returns>
10public static E ConvertIntToEnum<E>(int id, bool throwException)
11{
12    E enumValue = default(E);
13
14    if (Enum.IsDefined(typeof(E), id))
15    {
16        enumValue = (E)System.Enum.ToObject(typeof(E), id);
17    }
18    else
19    {
20        if (throwException)
21        {
22            throw new ArgumentException("Supplied enum id does not have a corrisponding enum");
23        }
24    }
25
26    return enumValue;
27}
Usage
Call the method as follows:

ConvertIntToEnum(2, false);

which will return the MyEnum item which matches '2'.