h1.post-title { color:orange; font-family:verdana,Arial; font-weight:bold; padding-bottom:5px; text-shadow:#64665b 0px 1px 1px; font-size:32px; } -->

Pages

Enumeration in C#.Net

It is a Special format of Value Type.
Inherited from System.Enum Class.
Consists of some underlying data type.
All members in an enum are Public members.
How to create enumeration?
enum Family
{
Father, Mother, Son, Daughter
}
How to use enum keyword in C#.net Program?
Create a Project in the VS 2008 using C# language.
Open you form Code view.
Copy and Paste this Code with Class.
enum Company
{
IBM,
GANTEC,
INTEL,
HP
}
Here ,Company is name of the enum.
Now we will call enum value in the form loading event.
I want to display a value of enum value using MessageBox.
So declare a MessageBox.Show(“”) in the foem Load event.
MessageBox.Show(Company.GANTEC.ToString());
Please note this we use ToString() Method .Why we use this?Because MessageBox show method Parameter is string.you can use differennt way.
MessageBox.Show(Convert.ToString(Company.GANTEC));
Or
string str = Company.GANTEC.ToString();
MessageBox.Show(str);
It depends upon user choice.
How to get Integer value from enum?
enum Company
{
IBM =1,
GANTEC,
INTEL,
HP
}
In this example , I declared value for IBM.now, I want to display a integer value from enum.So I used below code in the Load Event.
int i = (int)Company.GANTEC;
MessageBox.Show(i.ToString());
User can view 2. we intialized first Value of enum is 1.So automatically,enum add a values.SO we get 2.Suppose ,user uses this way.
enum Company.
{
IBM =1,
KRISH,
GANTEC=1,
INTEL,
HP
}
int i = (int)Company.IBM;
MessageBox.Show(i.ToString());
int i = (int)Company. INTEL;
MessageBox.Show(i.ToString());
User will get 1 for IBM and 2 for INTEL.
Some useful Tips :
We can give same values to two enum members.
The values of enum cannot be changed
An enum cannot have tow members with same name.
We can’t inherit from enums.