14,734,298 members
See more:
Hi, I have an enum called Gender and I was wondering how I would cast the enum to a random int between 0 and 1.
```public enum Gender : int
{
Male = 0,
Female = 1,
}```
Posted
Updated 9-Dec-13 20:23pm
v2

## Solution 1

I am not sure. Just give a try good luck.

Random rnd1 = new Random();
Gender g = (Gender)rnd1.Next(2);
Karthik_Mahalingam 10-Dec-13 1:46am

this will work fine..

## Solution 2

The Enum you show is equivalent to:
```public enum Gender
{
Male,
Female
}```
Here's an example of a method that will return either Gender.Male or Gender.Female at random:
```Random rand = new Random();

private Gender randomGender()
{
return (rand.Next(2) == 0) ? Gender.Male : Gender.Female;
}```
This uses the overload of the .Next method of the Random Class that takes an integer and returns an integer value that is positive and less than the supplied integer parameter.

If you really need to get an integer back:
```private int randomGenderAsInt()
{
return Convert.ToInt32((rand.Next(2) == 0) ? Gender.Male : Gender.Female);
}```
But, consider the required conversion to integer may not be necessary; remember than an Enum can be used directly in such constructs as a switch/case statement:
```private void GenderDemo(int howMany)
{
for (int i = 0; i < howMany; i++)
{
Gender theGender = randomGender();

switch (theGender)
{
case Gender.Male:
// code for 'Male here
break;
case Gender.Female:
// code for 'Female here
break;
}
}
}```
One of the many useful purposes of Enums is to make code more readable, and easier to maintains, and extend.