Open E-School

Friday, February 24, 1984

What is an Enum and when should you use an Enum

Category: Programming Date: Monday, March 23, 2015

An Enum is a user defined datatype just like a class and a structure. Enum is the short form of the word Enumeration which means numbering of items. You should use the enum data types when you have a group of items which you want to group together and give them a name.

Let’s take an example

Suppose you create a class Student in your code

class Student  {      int rollNumber;      string name;      ????  gender;  }

We have three data members in this class. RollNumber is of the type int, name is of the type string. Now think what should be the data type for gender field? You will say that we will make gender as int and if the user enters 1 we will consider it as male and if the user enters 2 we will consider it as female. Then what will happen if the user enters 10? Will the compiler tell us that 10 is not the correct input for gender? No. If you think we will make gender as character and keep m for male and f for female then if the user enters z as the gender then will the compiler or the program tell us that its a wrong choice? No.

Let’s see how enums can help us in this situation

There is an answer to the above problem in programming and it is by using an enum. Below we have created an enum called gender

enum Gender  {      Male,      Female  }

Here we have created a new user defined data type called Gender. It is of the type enum and has two options Male and Female. By default Male will get integer value 0 and Female will get integer value 1. Whenever you create an enum the system will give unique integer values starting from 0 and incrementing by 1 to all the members of the enum.

Now we can write the student class again as shown below

class Student  {      int rollNumber;      string name;      Gender  gender;  }

Now when assigning a gender to the student you only have two choices to choose from. Either male or female. There is no other way to assign a gender to the student.

When should you use enums ?

Enums should be used when you have a set of choices to choose from and you do not want the user the select a choice outside the give set of options.

Rate this article and help us improve

Please Login to rate
Overall ratings: 0 | Rating: out of 5
Previous Article Next Article

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp