Click here to Skip to main content
15,887,175 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.
C#
public enum Gender : int
{
    Male = 0,
    Female = 1,
}
Posted
Updated 9-Dec-13 19:23pm
v2

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

Random rnd1 = new Random();
Gender g = (Gender)rnd1.Next(2);
 
Share this answer
 
Comments
Karthik_Mahalingam 10-Dec-13 1:46am    
this will work fine..
The Enum you show is equivalent to:
C#
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:
C#
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:
C#
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.
 
Share this answer
 

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