shanish
shanish

Reputation: 1984

Cast enum to integer

I have an enum class called Gender, and I have values in this like:

public enum GENDER
{
    MALE = 1,
    FEMALE = 2,
    OTHERS = 3,
}

And in my business object I just created a property for this, like:

public GENDER Gender
{
  get
  { 
      return gender; 
  }
  set 
  {
      gender = value; 
  }
}

In my database it's in type integer. For this I tried to assign the Gender value in the add function by its name Gender. But it's showing an error. Is it possible to cast the enum to integer so that it'll get the value automatically.

How can I fix this?

Upvotes: 1

Views: 2429

Answers (7)

CM90
CM90

Reputation: 855

The previous answers is right on it. Gender is now a type, just like int, so you can cast accordingly - both ways, too:

(int)Gender = . . .
/* Or */
(Gender)int = . . .

so, for

int i = (int)GENDER.male;

i would equal 1.

And the same for

Gender = GENDER.male;
i = (int)Gender;

i would also be 1.

Upvotes: 1

S2S2
S2S2

Reputation: 8502

The following examples should suffice:

int val = (int)Gender.Male;
int val2 = (int)_gender;

There are also System.Enum methods to help you discover and manipulate enum values like:

Console.WriteLine("The values of the Gender Enum are: ");
foreach (int i in Enum.GetValues(typeof(Gender)))
{
    Console.WriteLine(i);
}

Upvotes: 1

Adam Houldsworth
Adam Houldsworth

Reputation: 64467

Enums by default "inherit" from int (they are stored in int by default unless you choose another integral type), so you can simply cast to and from int without any trouble:

int i = (int)GENDER.MALE;

GENDER g = (GENDER)2;

Note that implicit casting is not supported. Casting must be explicit.

Beware that the cast doesn't do any checks of the range, so you can cast an int that doesn't have a GENDER value into a GENDER variable without error:

GENDER g = (GENDER)26;

Upvotes: 3

KF2
KF2

Reputation: 10143

If you want to set the database value to gender property, do this:

yourintdatabasefiled = (int)GENDER.yourproperty

Upvotes: 1

Eric Andres
Eric Andres

Reputation: 3417

You should be able to use a cast to convert between an integer and an enum value.

int n = (int)GENDER.MALE;

GENDER g = (GENDER)1;

If you're dealing with a string that you are reading from a database column (or any string for that matter) you can do the following:

GENDER g = (GENDER) Enum.Parse(typeof(GENDER), "MALE");

Note that Enum.Parse returns an object, so you have to cast it to your enum type first.

Upvotes: 1

FingerTheCat
FingerTheCat

Reputation: 77

If (int)Gender is not enough to fix your cast issue, try to add int.Parse(var, int) in your code. It might be helpful...

Upvotes: 1

MNGwinn
MNGwinn

Reputation: 2394

(int)Gender will do it. To cast a specific value instead of the property, you'll do something like (int)GENDER.MALE;

Upvotes: 5

Related Questions