Click here to Skip to main content
14,734,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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,
Updated 9-Dec-13 20:23pm

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..
The Enum you show is equivalent to:
public enum Gender
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
            case Gender.Female:
                // code for 'Female here
One of the many useful purposes of Enums is to make code more readable, and easier to maintains, and extend.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900