By jim

2009-06-03 06:46:39 8 Comments

I have a class called Questions (plural). In this class there is an enum called Question (singular) which looks like this.

public enum Question
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6

In the Questions class I have a get(int foo) function that returns a Questions object for that foo. Is there an easy way to get the integer value off the enum so I can do something like this Questions.Get(Question.Role)?


@GinCanhViet 2019-08-12 03:27:28


Question question = Question.Role;
int value = question.GetHashCode();

It will result in value == 2.

This is only true if the enum fits inside an int.

@RB. 2019-08-14 14:59:13

This is only true if the enum fits inside an int of course, as GetHashCode returns an integer.

@user12053089 2019-09-14 13:40:23


Question question = Question.Role;
int value = Convert.ToInt32(question);

@Jeff 2019-03-02 17:55:26

I came up with this extension method that includes current language features. By using dynamic, I don't need to make this a generic method and specify the type which keeps the invocation simpler and consistent:

public static class EnumEx
    public static dynamic Value(this Enum e)
        switch (e.GetTypeCode())
            case TypeCode.Byte:
                return (byte) (IConvertible) e;

            case TypeCode.Int16:
                return (short) (IConvertible) e;

            case TypeCode.Int32:
                return (int) (IConvertible) e;

            case TypeCode.Int64:
                return (long) (IConvertible) e;

            case TypeCode.UInt16:
                return (ushort) (IConvertible) e;

            case TypeCode.UInt32:
                return (uint) (IConvertible) e;

            case TypeCode.UInt64:
                return (ulong) (IConvertible) e;

            case TypeCode.SByte:
                return (sbyte) (IConvertible) e;

        return 0;

@Chad Grant 2019-12-27 19:05:09

please no, you could do all this in one line Convert.Changetype(e, e.GetTypeCode()) and get an object back, no need for dynamics or an extension method

@Gauravsa 2018-07-27 06:29:29

public enum Suit : int
    Spades = 0,
    Hearts = 1,
    Clubs = 2,
    Diamonds = 3

Console.WriteLine((int)(Suit)Enum.Parse(typeof(Suit), "Clubs"));

// From int

// From a number you can also
Console.WriteLine((Suit)Enum.ToObject(typeof(Suit), 1));

if (typeof(Suit).IsEnumDefined("Spades"))
    var res = (int)(Suit)Enum.Parse(typeof(Suit), "Spades");
    Console.Out.WriteLine("{0}", res);

@Peter Mortensen 2019-12-08 17:36:03

suit - "10. (card games) Each of the sets of a pack of cards distinguished by color and/or specific emblems, such as the spades, hearts, diamonds or clubs of traditional Anglo, Hispanic and French playing cards."

@Peter Mortensen 2019-12-08 17:42:49

An explanation of the sample code would be in order (by editing your answer, not here in comments).

@Chad Grant 2019-12-27 18:59:53

zero is generally reserved for unset / unkown state in enums, unusual to define it like that

@VPP 2016-04-12 07:09:30

In Visual Basic, it should be:

Public Enum Question
    Role = 2
    ProjectFunding = 3
    TotalEmployee = 4
    NumberOfServers = 5
    TopBusinessConcern = 6
End Enum

Private value As Integer = CInt(Question.Role)

@Ctrl S 2018-11-19 13:37:00

The question is for C#.

@Peter Mortensen 2019-12-08 17:33:28

The title says "Get int value from enum in C#".

@Vivek 2015-08-03 07:12:01

The example I would like to suggest "to get an 'int' value from an enum", is

public enum Sample
    Book = 1, 
    Pen = 2, 
    Pencil = 3

int answer = (int)Sample.Book;

Now the answer will be 1.

@Erik Karlsson 2015-06-26 16:51:09

My favourite hack with int or smaller enums:


For an enum

public enum Test
    Min = Int32.MinValue,
    One = 1,
    Max = Int32.MaxValue,


var values = Enum.GetValues(typeof(Test));

foreach (var val in values)




It doesn't work for enums based on long.

@Doug 2014-09-27 01:30:47

Maybe I missed it, but has anyone tried a simple generic extension method?

This works great for me. You can avoid the type cast in your API this way but ultimately it results in a change type operation. This is a good case for programming Roslyn to have the compiler make a GetValue<T> method for you.

    public static void Main()
        int test = MyCSharpWrapperMethod(TestEnum.Test1);

        Debug.Assert(test == 1);

    public static int MyCSharpWrapperMethod(TestEnum customFlag)
        return MyCPlusPlusMethod(customFlag.GetValue<int>());

    public static int MyCPlusPlusMethod(int customFlag)
        // Pretend you made a PInvoke or COM+ call to C++ method that require an integer
        return customFlag;

    public enum TestEnum
        Test1 = 1,
        Test2 = 2,
        Test3 = 3

public static class EnumExtensions
    public static T GetValue<T>(this Enum enumeration)
        T result = default(T);

            result = (T)Convert.ChangeType(enumeration, typeof(T));
        catch (Exception ex)

        return result;

@Tim Keating 2014-11-11 17:32:34

Possibly because doing (int)customFlag is less typing all around and does more or less the same thing?

@Peter Mortensen 2019-12-08 17:27:43

Re "Maybe I missed it, but has anyone tried a simple generic extension method?": SixOThree said "Use an extension method instead" and Bronek said "You can do this by implementing an extension method to your defined enum type".

@plavozont 2014-09-19 05:42:30

One more way to do it:

Console.WriteLine("Name: {0}, Value: {0:D}", Question.Role);

It will result in:

Name: Role, Value: 2

@SixOThree 2014-04-21 02:51:42

Use an extension method instead:

public static class ExtensionMethods
    public static int IntValue(this Enum argEnum)
        return Convert.ToInt32(argEnum);

And the usage is slightly prettier:

var intValue = Question.Role.IntValue();

@Grx70 2013-01-28 13:52:52

The easiest solution I can think of is overloading the Get(int) method like this:

[modifiers] Questions Get(Question q)
    return Get((int)q);

where [modifiers] can generally be same as for the Get(int) method. If you can't edit the Questions class or for some reason don't want to, you can overload the method by writing an extension:

public static class Extensions
    public static Questions Get(this Questions qs, Question q)
        return qs.Get((int)q);

@Bronek 2012-12-09 22:09:56

You can do this by implementing an extension method to your defined enum type:

public static class MyExtensions
    public static int getNumberValue(this Question questionThis)
        return (int)questionThis;

This simplifies getting the int value of the current enum value:

Question question = Question.Role;
int value = question.getNumberValue();


int value = Question.Role.getNumberValue();

@Benjamin Gruenbaum 2012-12-10 00:28:00

Bronek, what you did is make up uninformative syntax through a (non generic btw) extension method that actually takes longer to write. I fail to see how it is better than the original solution by Tetraneutron. Let us not make this into a chat, help is always welcome in stackoverflow and everyone here is here to help. Please take my comment as constructive criticism.

@Bronek 2012-12-10 03:20:15

Benjamin,first of all,why did you delete my comment?I don't understand your decisions-maybe somebody else through the community would agree with my comment.Secondly,my solution wraps Tetraneutron's one and accurately it is easier and less writing because an extension method is suggested by IntelliSense.So I think your decision is not impartial and representative.I see many similar answering on Stack and it is OK.Anyway I use my solution and maybe there are some people would choose my solution in the future,but these negative points make it harder to find.Most of all it is correct and not copy.

@Benjamin Gruenbaum 2013-08-07 14:45:58

@Bronek If you don't ping me I get no indication that you replied. I did not delete your comment I do not have the ability or want to do so. Likely a mod came by and deleted it - you're welcome to flag it for moderator attention and ask why or better yet - ask on Meta Stack Overflow. I have an opinion about your solution from a programming stand point which is perfectly in my right - this is what comments are for to begin with, no need to take it personal.

@Mathijs Van Der Slagt 2012-06-10 22:58:20

If you want to get an integer for the enum value that is stored in a variable, for which the type would be Question, to use for example in a method, you can simply do this I wrote in this example:

enum Talen
    Engels = 1, Italiaans = 2, Portugees = 3, Nederlands = 4, Duits = 5, Dens = 6

Talen Geselecteerd;    

public void Form1()
    Geselecteerd = Talen.Nederlands;

// You can use the Enum type as a parameter, so any enumeration from any enumerator can be used as parameter
void VeranderenTitel(Enum e)
    this.Text = Convert.ToInt32(e).ToString();

This will change the window title to 4, because the variable Geselecteerd is Talen.Nederlands. If I change it to Talen.Portugees and call the method again, the text will change to 3.

@WiseStrawberry 2019-01-09 14:57:07

coding in dutch. oh dear.

@Greg 2019-02-04 18:38:32

Unfortunately, this approach gives poor performance the more you use it. I tried it in some code of mine, and as time went on, my application got slower and slower, with less and less CPU usage. This implied that the threads were waiting on something - I'm assuming some kind of garbage collection, possibly due to boxing the enum parameter to ToInt32(). By switching to a simple int.Parse(), I was able to eliminate this poor performance completely, and the performance stayed the same no matter how long the code ran.

@Nathon 2011-07-22 20:56:19

To ensure an enum value exists and then parse it, you can also do the following.

// Fake Day of Week
string strDOWFake = "SuperDay";

// Real Day of Week
string strDOWReal = "Friday";

// Will hold which ever is the real DOW.
DayOfWeek enmDOW;

// See if fake DOW is defined in the DayOfWeek enumeration.
if (Enum.IsDefined(typeof(DayOfWeek), strDOWFake))
    // This will never be reached since "SuperDay"
    // doesn't exist in the DayOfWeek enumeration.
    enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWFake);
// See if real DOW is defined in the DayOfWeek enumeration.
else if (Enum.IsDefined(typeof(DayOfWeek), strDOWReal))
    // This will parse the string into it's corresponding DOW enum object.
    enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWReal);

// Can now use the DOW enum object.
Console.Write("Today is " + enmDOW.ToString() + ".");

@sooraj 2009-09-25 10:43:14


public Enum EmpNo
    Raj = 1,

And in the code behind to get the enum value:

int setempNo = (int)EmpNo.Raj; // This will give setempNo = 1


int setempNo = (int)EmpNo.Rahul; // This will give setempNo = 2

Enums will increment by 1, and you can set the start value. If you don't set the start value it will be assigned as 0 initially.

@Peter Mortensen 2016-01-07 20:04:00

Does this actually compile?

@Timothy Gonzalez 2016-11-14 21:58:04

Can something that is a Raj be also be a Rahul or a Priyanka? Your values conflict and should double to be unique e.g. 0, 1, 2, 4, 8, etc. This is my core concern with enums.

@derHugo 2019-10-10 22:30:49

@TimothyGonzalez actually enums simply count 1 up if you don't explicitly specify their value ;)

@Timothy Gonzalez 2019-10-11 14:57:49

@derHugo that depends if you assume the numerical values to be base 10 or base 2.

@derHugo 2019-10-11 14:59:48

@TimothyGonzalez well there is not much to assume ... I just pointed out that by default they do just count up 1 in int except you explicitly define otherwise

@Michael Petrotta 2009-06-03 06:51:59

It's easier than you think - an enum is already an int. It just needs to be reminded:

int y = (int)Question.Role;
Console.WriteLine(y); // Prints 2

@mqp 2009-06-03 06:56:05

Nitpick: this enum is already an int. Other enums might be different types -- try "enum SmallEnum : byte { A, B, C }"

@Michael Petrotta 2009-06-03 06:59:04

Absolutely true. C# reference: "Every enumeration type has an underlying type, which can be any integral type except char."

@Jeffrey Ferreiras 2017-12-06 05:14:37

Since enums can be declared with multiple primitive types, a generic extension method to cast any enum type can be useful.

enum Box

public static void UseEnum()
    int height = Box.HEIGHT.GetEnumValue<int>();
    int width = Box.WIDTH.GetEnumValue<int>();
    int depth = Box.DEPTH.GetEnumValue<int>();

public static T GetEnumValue<T>(this object e) => (T)e;

@Kamran Shahid 2016-12-16 06:58:06

Following is the extension method

public static string ToEnumString<TEnum>(this int enumValue)
    var enumString = enumValue.ToString();
    if (Enum.IsDefined(typeof(TEnum), enumValue))
        enumString = ((TEnum) Enum.ToObject(typeof (TEnum), enumValue)).ToString();
    return enumString;

@JohnLBevan 2013-03-30 01:08:55

I have recently converted away from using enums in my code in favour of instead using classes with protected constructors and predefined static instances (thanks to Roelof - C# Ensure Valid Enum Values - Futureproof Method).

In light of that, below's how I'd now approach this issue (including implicit conversion to/from int).

public class Question
    // Attributes
    protected int index;
    protected string name;
    // Go with a dictionary to enforce unique index
    //protected static readonly ICollection<Question> values = new Collection<Question>();
    protected static readonly IDictionary<int,Question> values = new Dictionary<int,Question>();

    // Define the "enum" values
    public static readonly Question Role = new Question(2,"Role");
    public static readonly Question ProjectFunding = new Question(3, "Project Funding");
    public static readonly Question TotalEmployee = new Question(4, "Total Employee");
    public static readonly Question NumberOfServers = new Question(5, "Number of Servers");
    public static readonly Question TopBusinessConcern = new Question(6, "Top Business Concern");

    // Constructors
    protected Question(int index, string name)
        this.index = index; = name;
        values.Add(index, this);

    // Easy int conversion
    public static implicit operator int(Question question) =>
        question.index; //nb: if question is null this will return a null pointer exception

    public static implicit operator Question(int index) =>        
        values.TryGetValue(index, out var question) ? question : null;

    // Easy string conversion (also update ToString for the same effect)
    public override string ToString() =>;

    public static implicit operator string(Question question) =>

    public static implicit operator Question(string name) =>
        name == null ? null : values.Values.FirstOrDefault(item => name.Equals(, StringComparison.CurrentCultureIgnoreCase));

    // If you specifically want a Get(int x) function (though not required given the implicit converstion)
    public Question Get(int foo) =>
        foo; //(implicit conversion will take care of the conversion for you)

The advantage of this approach is you get everything you would have from the enum, but your code's now much more flexible, so should you need to perform different actions based on the value of Question, you can put logic into Question itself (i.e. in the preferred OO fashion) as opposed to putting lots of case statements throughout your code to tackle each scenario.

NB: Answer updated 2018-04-27 to make use of C# 6 features; i.e. declaration expressions and lambda expression body definitions. See revision history for original code. This has the benefit of making the definition a little less verbose; which had been one of the main complaints about this answer's approach.

@Lankymart 2013-08-02 10:40:29

I guess it's the trade off between explicit cast and the code you have to write to circumvent it. Still love the implementation just wish it wasn't so lengthy. +1

@James Haug 2016-09-08 16:13:08

I've used several different type of classes structured similar to this. I find they work wonders when trying to follow the "don't let me be an idiot later" methodology.

@WonderWorker 2014-03-31 16:35:56

public enum QuestionType
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
} a fine declaration.

You do have to cast the result to int like so:

int Question = (int)QuestionType.Role

Otherwise, the type is still QuestionType.

This level of strictness is the C# way.

One alternative is to use a class declaration instead:

public class QuestionType
    public static int Role = 2,
    public static int ProjectFunding = 3,
    public static int TotalEmployee = 4,
    public static int NumberOfServers = 5,
    public static int TopBusinessConcern = 6

It's less elegant to declare, but you don't need to cast it in code:

int Question = QuestionType.Role

Alternatively, you may feel more comfortable with Visual Basic, which caters for this type of expectation in many areas.

@PablosBicicleta 2012-06-15 19:28:37

Declare it as a static class having public constants:

public static class Question
    public const int Role = 2;
    public const int ProjectFunding = 3;
    public const int TotalEmployee = 4;
    public const int NumberOfServers = 5;
    public const int TopBusinessConcern = 6;

And then you can reference it as Question.Role, and it always evaluates to an int or whatever you define it as.

@CAD bloke 2013-05-15 23:16:22

I'd use static readonly int because constants are compiled into their hard values. See

@thgc 2014-04-12 18:24:41

This solution actually doesn't provide the real benefit of strongly typed enums. If I only wanted to pass a GameState-enum-parameter to a specific method for example, the compiler shouldn't allow me to pass any int-variable as a parameter.

@blockloop 2014-08-14 17:11:55

@CADBloke which is precisely why you would use const and not static readonly because every time you compare static readonly you're making a method call to get the value of the variable whereas with a const you're comparing two value types directly.

@CAD bloke 2014-08-15 10:57:48

@brettof86 Yes, a const would be faster, if the compilation limitation will never be problem then it's all good.

@Zack 2015-04-22 14:05:25

@CADbloke What do you mean by "compilation limitation" here? Do you use static readonly int because you are loading the values dynamically from a settings file or something? I think if you are using this static class in place of an enum that it should be a const because the values will not change.

@CAD bloke 2015-04-22 21:53:09

@Zack I didn't explain that very well, by compilation limitation I mean that the value is hard-coded when you compile it so any change to that value would require that all assemblies using it need to be recompiled. I'm inclined to agree with you about usage because changing the values would have far-reaching implications.

@David Mårtensson 2016-03-16 13:53:20

The problem with this solution (we use it our self) is that it will not be obvious from the method signature what constants to use and there will be no compile time checking of valid entries. But aside from that this works very good.

@Timothy Gonzalez 2016-11-14 20:59:25

I was looking for an alternative, but this looks to be the best option with all the complexity, as pointed out in the top answers, involved in converting an enum to int.

@quemeful 2017-02-09 16:29:30

In my opinion this answer is the best, for development speed and readability. The compilation limitation, if any, is totally worth it.

@kitsu.eb 2017-10-05 23:49:14

I'm using this in an Azure Table, where enums are not supported anyway!

@MIKE 2018-02-01 02:21:32

clever! casting each enum is so ugly to look at

@Chad Grant 2019-12-27 19:03:20

This has nothing to do with enums / enumerations

@Tetraneutron 2009-06-03 06:49:18

Just cast the enum, e.g.

int something = (int) Question.Role;

The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int.

However, as cecilphillip points out, enums can have different underlying types. If an enum is declared as a uint, long, or ulong, it should be cast to the type of the enum; e.g. for

enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};

you should use

long something = (long)StarsInMilkyWay.Wolf424B;

@Jaider 2012-06-28 20:47:57

@Harry it isn't true. You can create Enumeration without casting, it is not required. and I only assign number in special cases, most of the time, I leave it as default value. but you can do enum Test { Item = 1 } and see that 1 == (int)Test.Item is equal.

@Sinthia V 2012-07-26 19:02:32

@Jaider (int)Test.Item That is a cast! () is the explicit cast operator.

@Paul Ridgway 2012-08-17 18:30:11

@Sinthia V he said you can create it without casting, which is correct

@quaylar 2013-10-29 16:14:19

If the underlying type for enum Question was not int but long this cast will truncate Roles integral value!

@El Mac 2015-04-08 09:19:06

@PaulRidgway that wasn't the question.

@ErikE 2015-08-13 07:00:24

You're right, of course. I was forgetting my programming language (in some languages, a long is a 32-bit signed integer). Of course a 64-bit integer goes up to 9.2 quintillion!

@percebus 2015-08-18 16:52:31

When you accept an Enum as a parameter, you know is only a fixed number of possible integral values you can get. On the other hand, if you take simply an int, then you have to validate if that int is within the accepted values., thus complicating the code. You can always override your signatures like ``` public void MyMethod(int x) { // do something with x } public void MyMethod(Enum x) { this.MyMethod((int) x); } ````

@MonsterMMORPG 2016-07-25 21:07:52

and for the opposite?

@Neil Busse 2018-02-09 17:52:09

I would shy away from using Long and Enum, but there might be a specific use case where that would actually make sense.

@cecilphillip 2010-07-09 14:54:16

Since Enums can be any integral type (byte, int, short, etc.), a more robust way to get the underlying integral value of the enum would be to make use of the GetTypeCode method in conjunction with the Convert class:

enum Sides {
    Left, Right, Top, Bottom
Sides side = Sides.Bottom;

object val = Convert.ChangeType(side, side.GetTypeCode());

This should work regardless of the underlying integral type.

@aboy021 2011-07-05 23:20:54

This technique proved its worth to me when dealing with a generic type where T:enum (actually T:struct, IConvertible but that's a different story).

@Mark Lakata 2012-11-09 02:15:11

How would you modify this to print out the hexadecimal value of side? This example shows the decimal value. The problem is that var is of type object, so you need to unbox it and it gets messier than I would like.

@Mesh 2013-10-23 08:20:48

I think you should change the example to object val = Convert...etc the var in your example will always be object.

@cecilphillip 2013-10-23 18:58:07

I don't think it matters much, but if it'll make the answer more clear... sure

@theLaw 2014-06-09 16:05:23

If you want to convert to int try (in case of an enum Sides : int) [...] object val = Convert.ChangeType(side, typeof(int)); [...]

@NickG 2014-08-06 09:58:20

You should always explicity set the int value of each enum option as the assigned number is not guaranteed and can vary by system. If you then build the DLL on another system, the enum values can change. This caused me a nightmare of a problem in the past when the enum values had to correspond with the values a database.

@Tim Abell 2015-03-23 20:24:58

@NickG can I ask what caused the assigned numbers to change? I ask because I've never heard of this and have always relied on the documented behaviour - "By default, the first enumerator has the value 0"

@NickG 2015-03-24 09:42:39

@TimAbell All I can really say is that we found that dynamically compiled aspx pages (where you have to deploy the .cs files to the live server) were assigning the integers differently to each value. That meant that serialised objects one one machine, were deserialising with different values on a different machine and effectively getting corrupted (causing hours of confusion). We raised it with MS and I seem to recall they said that the autogenerated integers were not guaranteed to be the same when built across different framework versions.

@NickG 2015-03-24 09:46:02

@TimAbell On a separate occasion, a developer deleted an obsolete/unused Enum value causing all other values in the sequence to be out by one. As such, our coding standards now require that IDs are always specified explicitly, otherwise adding/deleting or even auto-formatting the code (e.g. sorting alphabetically) will change all the values causing data corruption. I would strongly advise anyone to specify all Enum integers explicitly. This is ultra-important if they correlate to externally (database) stored values.

@Tim Abell 2015-03-24 13:30:51

Thanks for the info @NickG, that's some really valuable context. So if I can summarise: as soon as anything external to your program has knowledge of the integer values then any changes in them become a real problem and having explicit numbering makes subsequent breakage less likely.

@NickG 2015-03-24 13:32:48

Absolutely. Or if you suspect for any reason you might have to modify the enum values (including deleting or even reordering the code). I'd just always do it as there's no reason not to.

@Tim Abell 2015-03-24 13:57:34

I'd say "always" is overkill (the only absolute rule is there are no absolutes). If your enum never ventures outside the confines of your program then you're adding a minor overhead to editing the enum list by forcing people to figure out what the compiler would have done for you. Whether you care about modifications depends on where they're used. imho.

@Jeppe Stig Nielsen 2015-10-14 19:06:55

Getting a boxed (object) integer type is not very useful when you do not know the width of the integer type at compile-time! If you just want to write out the numerical value, use Sides side = Sides.Bottom; Console.WriteLine("{0:D}", side);. If you want a reference to the string, that is string sideStr = side.ToString("D");. And to answer the comment by @MarkLakata, just use X instead of D, that is Console.WriteLine("{0:X}", side) or side.ToString("X"). A lower-case x gives hexadecimal with lower-case digits a through f.

@JaimeArmenta 2014-09-18 22:53:47

int number = Question.Role.GetHashCode();

number should have the value 2.

@ThanhLD 2018-11-09 04:08:07

GetHashCode is one way to get value from Enum common mask

@AnorZaken 2020-02-18 13:57:49

Note that this is only "legit" for bool*, byte, ushort, int, and uint**. The GetHashCode for other types modifies the value, e.g. does some bitshifts and xors. (* 1 / 0, **casted to int of course). But all in all just don't do this unless it's your own private code.

@nawfal 2013-12-01 08:47:44

On a related note, if you want to get the int value from System.Enum, then given e here:

Enum e = Question.Role;

You can use:

int i = Convert.ToInt32(e);
int i = (int)(object)e;
int i = (int)Enum.Parse(e.GetType(), e.ToString());
int i = (int)Enum.ToObject(e.GetType(), e);

The last two are plain ugly. I prefer the first one.

@Johan B 2019-06-16 11:47:55

The second one is the fastest though.

@Sollace 2019-10-14 07:46:14

As someone who is used to using Mixins in Minecraft modding, the second seems like the obvious winner.

@Nalan Madheswaran 2014-01-14 20:28:07

Try this one instead of convert enum to int:

public static class ReturnType
    public static readonly int Success = 1;
    public static readonly int Duplicate = 2;
    public static readonly int Error = -1;        

@jerryjvl 2009-06-03 06:48:16

Question question = Question.Role;
int value = (int) question;

Will result in value == 2.

@Gishu 2009-06-03 06:51:01

The temporary variable question is unnecessary.

@jim 2009-06-03 06:51:13

So something like this Questions.Get(Convert.ToInt16(Question.Applications))

@Marc Gravell 2009-06-03 06:54:57

You can simply cast in either direction; the only thing to watch is that enums don't enforce anything (the enum value could be 288, even though no Question exists with that number)

@Guffa 2009-06-03 06:55:13

@jim: No, just cast the value: Questions.Get((int)Question.Applications);

@jim 2009-06-03 06:57:43

thanks everyone...I just want to be clear...casting Question.Role returns 2, the value and not 1 the index...correct?

@Michael Petrotta 2009-06-03 07:03:11

(though it'd be 0 for the index, but that's neither here nor there)

@Liam Laverty 2016-10-06 11:18:23

The temporary variable is unnecessary in production, but it makes it clear here in the answer that this is possible. The answer would be ambiguous without it.

@Felix D. 2017-12-16 16:10:50

@Gishu You could say it's ... questionable. ;)

Related Questions

Sponsored Content

67 Answered Questions

[SOLVED] What is the difference between String and string in C#?

42 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

12 Answered Questions

[SOLVED] What does the [Flags] Enum Attribute mean in C#?

  • 2008-08-12 04:09:16
  • Brian Leahy
  • 468181 View
  • 1411 Score
  • 12 Answer
  • Tags:   c# enums flags

27 Answered Questions

[SOLVED] How to cast int to enum?

  • 2008-08-27 03:58:21
  • lomaxx
  • 1325082 View
  • 3091 Score
  • 27 Answer
  • Tags:   c# enums casting int

27 Answered Questions

[SOLVED] How to get an enum value from a string value in Java?

  • 2009-03-02 22:56:34
  • Malachi
  • 1091572 View
  • 1934 Score
  • 27 Answer
  • Tags:   java enums

29 Answered Questions

[SOLVED] How to enumerate an enum

27 Answered Questions

[SOLVED] JavaScriptSerializer - JSON serialization of enum as string

21 Answered Questions

[SOLVED] Create Generic method constraining T to an Enum

37 Answered Questions

[SOLVED] String representation of an Enum

  • 2009-01-08 14:15:55
  • user29964
  • 754199 View
  • 902 Score
  • 37 Answer
  • Tags:   c# enums

Sponsored Content