.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Post New Resource Bookmark and Share   

Enumeration in C#.

Posted By:Narayanan       Posted Date: August 18, 2012    Points: 200    Category:    URL: http://www.dotnetspark.com  

Enumeration: 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 form Load event.

Code:

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.



     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend