Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 549 Vote(s) - 3.48 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Get int value from enum in C#

#1
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)`?
Reply

#2
Question question = Question.Role;
int value = (int) question;
Will result in `value == 2`.
Reply

#3
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;
}
Reply

#4
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.
Reply

#5
int number = Question.Role.GetHashCode();

`number` should have the value `2`.
Reply

#6
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());
Console.WriteLine(val);

This should work regardless of the underlying integral type.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through