Click here to Skip to main content
6,595,444 members and growing! (19,553 online)
Email Password   helpLost your password?
Languages » C# » Enumerations     Beginner License: The Code Project Open License (CPOL)

The Enum Keyword and Its Functional Usage

By santosh poojari

This article describes 'Static Methods' of the Enum Class
C# (C# 1.0, C# 2.0, C# 3.0), Dev
Posted:16 May 2008
Views:7,581
Bookmarked:16 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
6 votes for this article.
Popularity: 2.66 Rating: 3.42 out of 5

1

2

3
2 votes, 40.0%
4
3 votes, 60.0%
5

Introduction

The 'enum' Keyword is of Value Type. It is used to define integral constant and literals. It is inherited from the base class library(BCL) - 'Enum' where Enum's static methods are used by enum type for parsing enum values. This article tries to cover some of the enum functionality through code demonstration. Below is the source code which highlights various enum methods that are useful during the development phase.

Source Code

using System;
using System.Collections.Generic;
using System.Text;

namespace EnumSample
{
    class Program
    {
        public class EnumExamples
        {
            //Enum can also be derived from datatype-
            //Type byte, sbyte, short, ushort, int, uint, long, or ulong 
            public enum Status : byte
            { 
                REPORTED,
                OPEN,
                VERIFIED,
                CLOSED,
                REOPEN                
            }

            //Enum having Character Literal values
            public enum Colour 
            {
                RED='R',
                YELLOW='Y'                
            }

            //Enum having Numeric values
            public enum NumberType
            {
                WHOLE=0,
                NATURAl=1,
                EVEN=2,
                ODD=3
            }

            //MSDN --Example
            //http://msdn.microsoft.com/en-us/library/sbbt4032(VS.80).aspx
            [Flags]
            public enum CarOptions
            {
                SunRoof = 0x01,
                Spoiler = 0x02,
                FogLights = 0x04,
                TintedWindows = 0x08,
            }
            //END--

        }
        static void Main(string[] args)
        {
            //************************ENUM VALUES*******************************
            Console.WriteLine
                ("Output Enum Byte Value  : {0}",(byte)EnumExamples.Status.REPORTED);
            //Output Enum Byte Value  : 0
            Console.WriteLine("Output Enum Character Literal Value : 
                        {0}", (char)EnumExamples.Colour.RED);
            //Output Enum Character Literal Value : R
            Console.WriteLine("Output Enum Integer Value : {0}", 
                        (int)EnumExamples.NumberType.NATURAl);
            //Output Enum Integer Value : 1


            //************************ENUM NAMES*********************************
            Console.WriteLine("Output Enum Name as String Datatype : {0}",
                               EnumExamples.Status.REPORTED.ToString());
            //Output Enum Name as String Datatype :REPORTED
            Console.WriteLine("Output Enum Name as String Datatype : {0}",
                               EnumExamples.Colour.RED.ToString());
            //Output Enum Name as String Datatype :RED
            Console.WriteLine("Output Enum Name as String Datatype : {0}",
                               EnumExamples.NumberType.NATURAl.ToString());
            //Output Enum Name as String Datatype :NATURAL

            //****Enum.Parse--Input Parameter (typeof(enum),string)******
            Console.WriteLine("Output Enum.Parse Return As Typeof(Enum)
                               With IgnoreCase=False: {0}",
                               (EnumExamples.Status)Enum.Parse(typeof
                               (EnumExamples.Status), "REPORTED"));
            //Output Enum.Parse Return As Typeof(Enum) With 
              IgnoreCase=False: REPORTED
            Console.WriteLine("Output Enum.Parse Return As Typeof(Enum) 
                               With IgnoreCase=True: {0}", 
                               (EnumExamples.Status)Enum.Parse(typeof
                               (EnumExamples.Status), "reported", true));
            //Output Enum.Parse Return As Typeof(Enum) With 
              IgnoreCase=True: REPORTED

            //*****Enum.GetName--Input Parameter (typeof(enum),integer)*****
            Console.WriteLine("Output Enum.Parse Return As Typeof(Enum) :
                     {0}", Enum.GetName(typeof(EnumExamples.Status), 2));
            //Output Enum.Parse Return As Typeof(Enum) :VERIFIED
            
            
            //***Enum.ToObject --Input Parameter Can Be (Integer)|
              (Literal Constant)**
            Console.WriteLine("Output Enum.ToObject Return As Typeof(Enum) :
                     {0}", Enum.ToObject(typeof(EnumExamples.Colour), 'R'));
            //Output Enum.Parse Return As Typeof(Enum) :RED

            //******Enum.Format*********
            Console.WriteLine("Output Enum.Format Return As Typeof(Enum) :
                            {0}", Enum.Format(typeof(EnumExamples.Colour), 
                             EnumExamples.Colour.RED, "x"));
            //Output Enum.Format Return As Typeof(Enum) :00000052
            Console.WriteLine("Output Enum.Format Return As Typeof(Enum) : 
                              {0}", Enum.Format(typeof(EnumExamples.Colour),
                               EnumExamples.Colour.RED, "d"));
            //Output Enum.Format Return As Typeof(Enum) :82

            //****Enum.GetUnderlyingType *******
            Console.WriteLine("Output Enum.GetUnderlyingType Return Typeof
                               (Enum) : {0}", Enum.GetUnderlyingType(typeof
                               (EnumExamples.Colour)));
            //Output Enum.Format Return As Typeof(Enum) :System.Int32

            //****Enum.IsDefined-Input Parameter(Interger Only)for 'R'=82****
            Console.WriteLine("Output Enum.IsDefined Return as bool indicates
                    constant in the enum exist or not. : {0}", Enum.IsDefined
                   (typeof(EnumExamples.Colour), 82));
            //Output Enum.IsDefined Return as bool indicates constant in the
              enum exist or not.:82


            /*Enum.Names - To Load DropdownList--(TEXT)
             * Note that if one tries to load enum names into dropdownlist, one should
             * take note that enum only supports one word (no space).
            */
            int enumCounter = Enum.GetNames(typeof
             (EnumExamples.NumberType)).Length;                        
            foreach (string strName in Enum.GetNames(typeof
                   (EnumExamples.NumberType)))
            {
                Console.WriteLine("Enum for byte {0}: {1}", Enum.GetNames
          (typeof(EnumExamples.NumberType)).Length - enumCounter, strName);
                enumCounter--;
            }

            //Enum.Names - To Load DropdownList--(VALUE)
            int enumCounter1 = Enum.GetValues(typeof(EnumExamples.NumberType)).Length;
            foreach (int iValues in Enum.GetValues(typeof(EnumExamples.NumberType)))
            {
                Console.WriteLine("Enum for byte {0}: {1}", 
              Enum.GetValues
                  (typeof(EnumExamples.NumberType)).Length - enumCounter1, iValues);
                enumCounter1--;
            }
           
            //MSDN Example
            //http://msdn.microsoft.com/en-us/library/sbbt4032(VS.80).aspx
            EnumExamples.CarOptions options = EnumExamples.CarOptions.SunRoof
            | EnumExamples.CarOptions.FogLights;
            Console.WriteLine(options);
            Console.WriteLine((int)options);
            /* Output:
                SunRoof, FogLights
                5
            */
            /*
             * Notice that if you remove FlagsAttribute, 
             * the example will output the following:
             * 5
             * 5 
            */
            //END MSDN
            Console.Read();          
        }
    }
}

Feedback

I have tried to incorporate all the possible examples of enum which can be useful during development. Any suggestions or ideas about the functional usage of 'enum' will add more value to our learnings.

History

  • 16th May, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

santosh poojari


Member
He is a Team Lead currently working with one of the IT company in India.His overall experience in IT field is 7 years. He is a B.E (computers) graduate from Mumbai University.
His area of Interest is Microsoft Technology : Asp.Net,C#,Web services,SSIS,SSRS,Windows Workflow Foundation 3.0,SQL server 2005,State Machine Compiler,Regular Expression, Enterprise Library3.0,Spring.net,Design Patterns and Architecture Design.He is MCPD-EA Certified.

http://santoshpoojari.blogspot.com
Occupation: Team Leader
Location: India India

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 7 of 7 (Total in Forum: 7) (Refresh)FirstPrevNext
GeneralEnum.IsDefined is slow PinmemberLehi23:20 16 Jul '09  
GeneralI love enumerations PinmemberMember 15036454:32 16 May '08  
GeneralRe: I love enumerations PinmemberPIEBALDconsult5:54 16 May '08  
GeneralRe: I love enumerations PinmemberMember 15036456:39 16 May '08  
GeneralRe: I love enumerations PinmemberPIEBALDconsult10:19 16 May '08  
GeneralRe: I love enumerations Pinmembersantosh poojari19:57 18 May '08  
GeneralNice one for the beginners! Pinmemberjohannesnestler3:01 16 May '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 16 May 2008
Editor: Deeksha Shenoy
Copyright 2008 by santosh poojari
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project