We help IT Professionals succeed at work.

using Enum data type in constructor?

Raul77
Raul77 asked
on
Medium Priority
2,142 Views
Last Modified: 2012-05-06
Hi,
can someone make a simple example of using enum data type.
i know how to define them

public enum Gender { Male, Female }

but how can i pass it to constructor and use it there?
Comment
Watch Question

Commented:

public class MyClass
{
 
     public enum Gender { Male, Female }
 
     public MyClass(Gender theGender)
     {
            // do something with theGender variable
      }
 
}

Open in new window

Author

Commented:
mmm ok lets say i am making a human object,
the user specifies Male as gender, how to i pass it to my object

Gender = theGender;  ???
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
Like this you mean?

    MyClass mc = new MyClass(MyClass.Gender.Male);

Author

Commented:
i have a form that user signs up, the specify their gender
once they click submit
i want to create a user object

how can i pass to constructor what the user selected (male or female)
Commented:
By creating an ENUM you are essentially making a new type (like an integer) so you could have something like this:

Human  mH = new Human  (Human.Gender.Male, 33);

than you have an instance of a Human.  The Human class might look like this:
public class Human
{
 
     public enum Gender { Male, Female }
 
 
     private Gender mGender;
     private int mAge;
 
     public Human(Gender theGender, int theAge)
     {
            mGender = theGender;
            mAge = theAge;
     }
 
}

Open in new window

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
You already have an example of how to create a Human instance using the enum...are you asking how to read what was selected on the Form?

If so, we would need to see how you are calling the sign-up form and what you allowing the user to specify gender with...

Author

Commented:
perfect, Thanks
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.