What are Enums in C# using Sample code Example

 

In this blog tutorial of Onlinebuff.com we will understand all about Enumeration (enum) in c-sharp.

What are Enums?

In a single liner definition, Enums helps you to define, assign and maintain constants in a program in an effective way.

Enumeration in C-sharp is defined from "enum" keyword. Enums are strongly typed named constants means enum of one type may not be absolutely assigned to an enum of another type even though the underlying value are the same. Enums are value types and get allocated on stack. Since they are value types which means they cannot inherit or inherited from another enum type.

If you are looking to implement enum in your project then this is one of big advantage of implementing enum that it consume less memory space on the server since they are value types.

The group of named constant in a single set of enum scope is considered as enumerator list. They provides a concise way to assign names to a bunch of integers.

Enums are more manageable and improves readability of code because they provide symbolic named constants so you need to just remember the real names not the integer values.

Enums in c-sharp can be defined in two ways i.e lowercase enum which is inherits the base class Enum and uppercase enum using the Enum base class. You can use lowercase enum to implement enums and uppercase enum to create static enum methods.

Enum types are by default is integer but beside integer it can be double, sbyte, uint, short, long, float and byte just it has to type cast it.

Inside the scope of enum we have enumerator list elements the first element default value will always be 0 and followed by other elements values will increased by 1.

If you give any specific value to first element then other elements values will increased by 1.

Note : Multiple enum elements can have the same value.

Enumeration are of two types Simple Enumeration and Flags Enumeration.

Simple Enumeration means whose members contains only single value.

Flags Enumeration means whose members contains multiple values or multiple values which are combined using bitwise OR operator.Combinations of flags enumeration values are examined using bitwise AND operator.When we use the flags attribute with enum then each enumeration member value should have power of 2 like 1, 2, 4, 6, 8, 10, 12.....To compute the next value in the series, simply multiple the last value by 2 is because the way integers are represented by a computer.

Note : The flags attribute should be used when ever the enumerable represents a collection of values, rather than a single value.

Declaration Syntax
 
enum EnumName : DataType{

EnumElements1, EnumElement2

}

Enum is declared with "enum" keyword followed by enumname by default enum is of "int" datatype and inside the scope enum, enum elements declared separated by commas.

Simple Enumeration Sample Code

Let's demonstrate the simple example of enumeration using c-sharp code in console application.

 
class Program
    {
       
        public enum Animals
        {
            Lion = 1,
            Tiger = 2,
            Peacock = 3,
            Leopard = 4,
            Elephant = 5,
            EmuBird = 6
        }

        static void Main(string[] args)
        {

            Animals animalNames = (Animals)5;

            Console.WriteLine(animalNames);
            Console.WriteLine((int)animalNames);

            if (animalNames == Animals.Tiger)
            {
                Console.WriteLine("Tiger");
            }

            if (animalNames == Animals.Leopard)
            {
                Console.WriteLine("Leopard");
            }


           
        }
    }

Above the program will display output as shown below.

As you see in our above code that we have created a enum called "Animals" and inside the scope of enum we have provided the list of animal names with values. Now in our main program of console application we have created the enum object "animalNames" and assigned the value as 5 which is an elephant value. In the next line of code we have printed the animal-name and animal integral value and in the further line of code just to check we have also compared the value with other animal names.

Display Output Result

Elephant 5

Flags Attribute enum c# sample code

In this demonstration we will use Flags attribute and we will see how to use enum Flags attribute using c# code.

 
class Program
    {
        [Flags]
        public enum EPropertyTypes
        {
            Flats = 1,
            Villas = 2,
            Duplexus = 4,
            Office = 6,
            Shop = 8,
            Condos = 10
        }

        static void Main(string[] args)
        {

            EPropertyTypes allowedTypes = EPropertyTypes.Flats | EPropertyTypes.Shop;

            Console.WriteLine(allowedTypes);
            Console.WriteLine((int)allowedTypes);

            if ((allowedTypes & EPropertyTypes.Flats) == EPropertyTypes.Flats)
            {
                Console.WriteLine("Property Type is Flats");
            }

            if ((allowedTypes & EPropertyTypes.Condos) == EPropertyTypes.Condos)
            {
                Console.WriteLine("Property Type is Condos");
            }


        }
    }

Above the program will display output as shown below.

As you see from above sample code we have used [Flags] attribute with enum and as we discussed before also that when we use [Flags] attribute with enum then members of an enum should have power of 2 means you need to multiply the last value with 2. So same technique we have applied in our above example we have multiplied the last value of enum member i.e. Flats = 1 with 2 and rest member in series.

In our main program we have created an object of enum "allowedTypes" and assigned the multiple values separated by "OR" operator and to examine wheather that vaule present in that object we used "if-condition" along with "AND" operator compared with actual enum member. If true value will be printed or else will not be printed.

Advantages of using Enums

Enums are strongly typed means enum of one type cannot be assigned it to enum of another type.

Enums are named constant so the code becomes more simple, efficient, manageable and readable.So you need to just remember the real names not the integer values

Enums consumes less memory space because enums are value type and allocated on stack.

Enums are represented as strings but processed as an integer.

The default enumeration type is int, and other approved types are sbyte, byte, ushort, short, long, uint, and ulong.

Flags Enumeration provides us to assign the multiple values to an enum member or an enum object.

Why to use Enums over Constants ?

Enums are strongly typed named constants and benefits of using enums over constants is when you want to define a range of values for a particular Entity like for example defining range values for ExceptionHandling.

 

enum ExceptionHandling{

 ApplicationError,
 ArgumentNullException,
 SystemException,
 InnerException,
 IndexOutOfRangeException

}

or defining range values for Colors range like.

 
enum Colors{

 Green,
 Blue,
 Yellow,
 Violet,
 Red,
 Orange,
 Pink

}

Enums are also have the ability to define multiple collection values separated by Bitwise OR operator i.e. like FontStyle.Bold | FontStyle.Italic and on the otherhand constants are not named constant and they are not strongly typed they are just like a regular variables whose value cannot modify after the defination and can be used for single value entity like TaxExemptionRate, PIValue, HostUserIP, CountryID, WebExtension.

 

public const double TaxExemptionRate = 250000;
public const double PIValue = 3.14;
public const string CountryID = "IN";
public const string WebExtension = ".aspx";

Furthermore enums gives you more type safety for example if you use constants as method parameters then there is a possibility to call the method with any "integer" value but on the otherhand enum won't allow it to happen rather it clearly give us visual studio intellisense help to pass appropriate enum value without any confusion (i.e. because enums are named constants).

Conclusion : Use constants when you want to define different key values like a self-documentation code in a single place for an easy maintenance in an application.

Use enums for defining sequences and states (range of values) with type-safety and with improved readability.

Enumerating the Members of an Enumeration

In this we will demonstrate to display enum member names and values using FOR-EACH Loop and GetNames(Type) method that returns a string array of the enumeration members.

 

class Program {

        enum ZodiacNames 
        {

            Aries = 1,	
            Taurus = 23,
            Gemini = 34,
            Cancer = 45,
            Leo = 57,
            Virgo = 68,
            Libra = 77,	
            Scorpio = 89,
            Sagittarius = 99,
            Capricorn = 100,
            Aquarius = 110,
            Pisces = 140

        }
        static void Main(string[] args)
        {

            foreach (string _zodiacnames in Enum.GetNames(typeof(ZodiacNames)))
            {
                Console.WriteLine("{0} - {1}", _zodiacnames, (int)Enum.Parse(typeof(ZodiacNames), _zodiacnames));
            }

        }

        
 }

As you see from above snippet of code that we have used the GetNames method to loop through the enumerator list using FOR-EACH loop.If you run the above program you will get the following output as shown below. Enum.Parse we have discussed below.

Convert string to enum c# using Enum.Parse Function

In this demonstration we will convert input string value to an enum member using Enum.Parse method. Enum.Parse method converts strings to an equivalent enumerated object. Enum.Parse method takes a string and gets the actual enum constant from type of enum. Now let's do the small demonstration of Enum.Parse which takes a string and make it as enum object in this example we have used inbuilt "ConsoleColor enum" which is an background color enum of a console application and to this enum we will pass user input color name.

 

    class Program
    {

        static void Main(string[] args)
        {

            Console.WriteLine("Enter the Color Name");
            string strColor = Console.ReadLine();

            Console.BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), strColor);

        }
    }

As you see from above code that we have passed the user input string value to Enum.Parse method to covert string to an enum object. The above program output is shown below.

Input value is Red

//Output

Input value is Cyan

//Output

Note : To find the ConsoleColor Enum list just right click on ConsoleColor name --> Click on Go to Definition link. Sample as shown below.

 

namespace System
{
    // Summary:
    //     Specifies constants that define foreground and background colors for the
    //     console.
    [Serializable]
    public enum ConsoleColor
    {
        // Summary:
        //     The color black.
        Black = 0,
        //
        // Summary:
        //     The color dark blue.
        DarkBlue = 1,
        //
        // Summary:
        //     The color dark green.
        DarkGreen = 2,
        //
        // Summary:
        //     The color dark cyan (dark blue-green).
        DarkCyan = 3,
        //
        // Summary:
        //     The color dark red.
        DarkRed = 4,
        //
        // Summary:
        //     The color dark magenta (dark purplish-red).
        DarkMagenta = 5,
        //
        // Summary:
        //     The color dark yellow (ochre).
        DarkYellow = 6,
        //
        // Summary:
        //     The color gray.
        Gray = 7,
        //
        // Summary:
        //     The color dark gray.
        DarkGray = 8,
        //
        // Summary:
        //     The color blue.
        Blue = 9,
        //
        // Summary:
        //     The color green.
        Green = 10,
        //
        // Summary:
        //     The color cyan (blue-green).
        Cyan = 11,
        //
        // Summary:
        //     The color red.
        Red = 12,
        //
        // Summary:
        //     The color magenta (purplish-red).
        Magenta = 13,
        //
        // Summary:
        //     The color yellow.
        Yellow = 14,
        //
        // Summary:
        //     The color white.
        White = 15,
    }
}

So hey friends this all about the enumeration or enum in c-sharp if you have any doubt or query or if you think i have missed anything in enum to explain then feel free to let me know. The more the feed-back you give me the more we can improve this article. Aim of @OnlineBuff is to provide complete information so that using this blog post everyone of us should get more knowledge and benefit.

Kindly share this article on your social media networks...Thank you..Happy Programming...!

 

 

:: SHARE THIS POST ::

        
 

More C# Articles To Read Next:

 
Jun
16
2014

Understand the use of Override Keyword and New Keyword in C# with Example?

CLICK TO READ FULL ARTICLE

Views - 11896 |Category - C#

Jun
06
2014

Understand params parameter with an example in C#?

CLICK TO READ FULL ARTICLE

Views - 12678 |Category - C#

Mar
24
2014

C# While Loop with an example using break and continue statements inside while loop

CLICK TO READ FULL ARTICLE

Views - 12269 |Category - C#

Mar
20
2014

How to deploy an assembly into GAC(Global Assembly Cache) ?

CLICK TO READ FULL ARTICLE

Views - 20497 |Category - C#

Mar
14
2014

Understanding concept of Concat,Substring methods of a string class ?

CLICK TO READ FULL ARTICLE

Views - 5526 |Category - C#

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

7kk6j