C# > Enums

Enums in C#

How to use Enums in c#?


Enums:

Enum is a keyword which is a value type contains constants to declare the enumeration list. Enums are defined above the classes. For example we are having color as Enum it consists of red, Green, pink, blue as constants to declare the enumeration list.     

Why to use Enums

Enums are used to provide an efficient way to define a set of named integral constants that may be assigned to a variable. It also reduces the error which are occured by the mistyping numbers   

How to use enums in c#

Enums are grouped together in a enumeration list when there are different logical constants which are related to each other. First we have to create the enum keyword and it is must be declared to a value  such as for example am assigning the value to color and we must assign the enumeration list as red, green, blue, yellow. We have declare the program and assign the enum values which we have declared in enumeration list.        


Declaration of the Enum

public enum Borderside
{
    Left,Right,Top,Bottom
}

In the above code snippet we have declare how to use enum. We have defined the enum as borderside  and declared the left, right, top, bottom in borderside.     


Another Example for declaring the Enum 

public enum MyEnum
{
    const1,
    const2,
    const3
}

In the above code snippet we have defined how to use enums. We have defined enum as Myenum and we aredefining the enum values as const1, const2 and const3 in MyEnum   

Advantages of using Enums

The advantage of the enum is to make the function easy to change the values for the future. It also reduces the error which are occured by the mistyping numbers.    

Enums are not allocated in the memory they exist only in the compilation stage. Enum.parse throws an error if a value is incorrect. So we use Enum.IsDefined to check. So every helper method helps a enum a lot.      

Simple example program to define Enums:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public enum School
    {
        Students,
        Teachers,
        books,
        Games,
        library
        
    }

    class Program
    {
        static void Main(string[] args)
        {
            School vidya = School.Teachers;
            Console.WriteLine(vidya);

           
            Console.ReadLine();
        }
    }

In the above code snippet we had defined the enum. We have declared enum as School, In that enum School we have defined constants as students, Teachers, books, Games, library. We have defined class as program and in the main function of the program we have defined enum School  as vidya and declaring the enum school as Teachers. In the next line we are calling the console. writeline as (vidya), Which calls the value as enum school as Teachers in the output.

output

     

Enum conversions 

There are different types of enums they are 

  • Enum to Tostring
  • string to Enum
  • integer to enum 
  • enum to integer

Conversion of Enum to Tostring()

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class EnumSample
{
    enum Tutorials
    {
        csharp = 1,
        html = 2
    };

    public static void Main()
    {
        Enum MyTutorials = Tutorials.csharp;
        Console.WriteLine("Learn tutorials in www.techfunda.com '{0}'", mytutorials.ToString());
    }
}

In the above code snippet we have defined conversion of enum value to string. We have taken class as enumsample and we defined the enum as Tutorials and we declare the constants in csharp as csharp as1 and html as 2 and in the main function of the program we defined the enum as MyTutorials and assigned the value of csharp as tutorials.csharp and the console.writeline prints the value as learn tutorials in www.techfunda.com csharp in the output.   

output

Conversion of string to enum

Enum.parse is a method which is used to convert the string value to enum values.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
    enum Website
    {
        
        techfunda = 1,
        Dotnetfunda = 2,
        itfunda=3
    }

    static void Main()
    {
        
        string value = "Dotnetfunda";

        
        Website site = (Website)Enum.Parse(typeof(website), value);

       
        if (site == Website.Dotnetfunda)
        {
            Console.WriteLine("Dotnetfunda.");
        }
    }
}

In the above code snippet we have defined how to convert the string value to the enum. We need Enum .parse method to convert the string value to te enum value. In this example program we are taking class as program and declaring the enum as Website, we are declaring the enum values as techfunda, dotnetfunda and itfunda as 1, 2, 3. and in the main function of the program we are giving string value as dotnetfunda. In the nextline we are declaring  Website site = (Website)Enum.Parse(typeof(Website), value); which defines as we are declaring the Website name to site and enum.parse Type of(Website) defines the Website value and in the nextline we are checking the if condition if (site == Website.Dotnetfunda). If the string value is equal to dotnetfunda it prints the value as dotnetfunda, If the value of the string value is equal to dotnetfunda itshows an exception handled error in the output.

output

   

Conversion of Enum to Integer

The below program shows the conversions of enum value to integer value.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Enum
{
    enum Months { January=1, February, March, April, May, June, July };

    static void Main()
    {
        int x = (int)Months.January;
        int y = (int)Months.May;
        Console.WriteLine("Jan = {0}", x);
        Console.WriteLine("May = {0}", y);
    }
}

In the above code snippet we have defined how to convert the enum to int. We have taken class as enum and we have declared the enum as Month with the constants   as january, February, march, april, may,  june and july and in the main function of the class program we have declared the int x = (int)Months.January; this declares the month of january value and int y = (int)Months.May; declares the month value of the may and prints the values in the output . We have taken january value as 1 because the enum takes the values from zero.      

output

Conversion of Integer to Enum

The below program shows the conversion of integer value to enum value

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
    {
        public enum Monthofyear
        {
            January = 1, February, March, April, May, June, July, August, September, October, November, December
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Monthofyear {0} {1}", (int)Monthofyear.January, Monthofyear.January);
            Console.WriteLine("Monthofyear {0} {1}", (int)Monthofyear.February, Monthofyear.February);
            Console.WriteLine("Monthofyear {0} {1}", (int)Monthofyear.March, Monthofyear.March);
            Console.WriteLine("Monthofyear {0} {1}", (int)Monthofyear.April, Monthofyear.April);
            Console.WriteLine("Monthofyear {0} {1}", (int)Monthofyear.May, Monthofyear.May);
            Console.WriteLine("Monthofyear {0} {1}", (int)Monthofyear.June, Monthofyear.June);
            Console.WriteLine("Monthofyear {0} {1}", (int)Monthofyear.July, Monthofyear.July);
            Console.WriteLine("Monthofyear {0} {1}", (int)Monthofyear.August, Monthofyear.August);
            Console.WriteLine("Monthofyear {0} {1}", (int)Monthofyear.September, Monthofyear.September);
            Console.WriteLine("Monthofyear {0} {1}", (int)Monthofyear.October, Monthofyear.October);
            Console.WriteLine("Monthofyear {0} {1}", (int)Monthofyear.November, Monthofyear.November);
            Console.WriteLine("Monthofyear {0} {1}", (int)Monthofyear.December, Monthofyear.December);

            Console.ReadLine();
        }
    }

In the above code snippet we have converted the integer value to enum. In this program we are finding Monthofthe year , In the main function we have declared the Monthofyear values as january=1,february, march, april, may, june, july, august, september, october, november, december and declaring it into int values and The console.readline reads the output values as converting the int values to enum values

output

 

Flag enums:

Flags are used to hold multiple values to the enum by using bitwise operations. We can perform operations by using bitwise operators such as "|"and "&".   

Example program on Flag enums:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
    {
        [Flags]
        public enum Bordersides
        {
            No = 0, Left = 1, Right = 2, Top = 4, Bottom = 8
        }

        static void Main()
        {
            Bordersides leftright = Bordersides.Left | Bordersides.Right;

            if ((leftright & Bordersides.Left) != 0)
                Console.WriteLine("Includes left");   

            string formatted = leftright.ToString();

            Bordersides s = Bordersides.Left;
            s |= Bordersides.Right;
            Console.WriteLine(s == leftright);              

            s ^= Bordersides.Right;
            Console.WriteLine(s);                    
        }
    }

In the above code snippet we have defined the flag enums. We have taken class as program, We have declared flag Enum as Bordersides as no=0 left=1, right=2, Top=4 and bottom as 8 and in the main function of the class we have taken Bordersides leftright = Bordersides.Left | Bordersides.Right;  by using bitwise operators,  if ((leftright & Bordersides.Left) != 0)Console.WriteLine("Includes left"); here we are using if statement to check the condition if leftright and bordersides.left are not equal to zero it prints the output as includes left. and string.format =leftright Tostring, In the nextline we are usingBordersides s = Bordersides.Left; s= Bordersides.RightConsole.WriteLine(s == leftright); We have given the bordersides as s=bordersides as left and checking s with the operator by Bordersides.right and prints the output as left and s ^= Bordersides.Right; Console.WriteLine(s); here we are checking thes with the operator as Bordersides.right and prints the output as left


output


Enum.GetName

Enum.GetNames is a string represention. which are used to represent the values of the strings.

Example program  on Enum.GetName

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

class Program
{
    enum Websites
    {
        Dotnetfunda,
        itfunda,
        techfunda,
        kidsfunda,
        farmingfunda,
        fundoovideo
    };

    static void Main()
    {
        string name = Enum.GetName(typeof(Websites),
            Websites.techfunda);
        Console.WriteLine(name);

        name = Enum.GetName(typeof(Websites),
            0);
        Console.WriteLine(name);
    }
}

In the above code snippet we have defined the enum.GetName. We have defined class as Websites and in the enum we had defined enum as Websites with there constants names as techfunda, dotnetfunda, itfunda, kidsfunda, farmingfunda, fundoovideo, in the main function of the program we have string name = Enum.GetName(typeof(Websites),Websites.techfunda) which calls the string value of the constant s in the enum as techfunda in the output and name = Enum.GetName(typeof(Websites),0); calls the output value "0"as dotnetfunda, The enum takes the constant value from "0".  

output


Enum.Format    

Enum.Format is used to represent the string representation. It is used to represent the hexadecimal values or strore the values in digit format.

Example program on using Enum.Format

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
    enum Websites
    {
        techfunda,
        dotnetfunda,
        itfunda
    }

    static void Main()
    {
        M("D");
        M("d");
        M("X");
        M("x");
        M("F");
        M("f");
        
    }

    static void Main(string format)
    {
       
        string value = Enum.Format(typeof(Websites), Websites.itfunda, format);
        Console.WriteLine("{0} = {1}", format, value);
    }
}

In the above code snippet we had declared the Enum.Format. We have taken the class as program and we have declare the enum as Websites and declared the constants as techfunda, itfunda, dotnetfunda and in the main function of the program we have some constant values as m (X, x, D, d, F, f) are the constant values which are used in the format. These format are used to convert the values to hexadecimal values and the string value = Enum.Format(typeof(Websites), Websites.itfunda, format); Console.WriteLine("{0} = {1}", format, value); which formats the value as given as itfunda and the and D value as 2 and the x value as in hexadecimal value as 0000002

output

Switch Enum

An enum switch is used to produce the reults fater in a clear way. An enum can be used like switch statement to produce the values.   

Example program to define the switch Enum

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


public enum Sports
{
    Cricket,
    Football,
    Tennis
}


class EnumSwitch
{
    static void Main()
    {
        Sports Game = Sports.Football;

        switch (Game)
        {
            case Sports.Cricket:
                Console.WriteLine("Indians love cricket.");
                break;
            case Sports.Football:
                Console.WriteLine("No one shows keen interest in football in India.");
                break;
            case Sports.Tennis:
                Console.WriteLine("Tennis is popular Game.");
                break;
        }
        Console.ReadLine();
    }
}

In the above code snippet we have defined the Switch Enum and we declared the values as  cricket, Football and tennis. We have declared Sports as Game and defined sports as Football and we have taken switch cases as case1 w have Sports.cricket and in the case2 we have Sports.football and in case 3 we have Sports.Tennis. and prints the output as Sports.Football.

output

      

Enum operators

Enum also uses different kind of operators to perform operations between the values. There are different types of operators used in the enums

They are: 

  •  '+'(Addition operation)
  •  '-'(subtraction operation)
  •  '='(Assignment operator)
  •  '!='(Not equal to operator)
  •    '>'(Greater than)
  •  '<'(Less than operator)

Example program to define the  operators in enum 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
enum Alphabets
{
    a,
    b,
    c

}

class program
{
    public static void Main()
    {
        Console.WriteLine(Alphabets.a + 25);
        Console.WriteLine(45 - Alphabets.c);
        Console.WriteLine(Alphabets.a == Alphabets.a);
        Console.WriteLine(Alphabets.a != Alphabets.a);
        Console.WriteLine(Alphabets.a < Alphabets.c);
        Console.WriteLine(Alphabets.a > Alphabets.c);

    }
}

In the above code snippet we had defined how to use enum operators in c#. We have taken class as program and we declared enum as Alphabets and declared the constants of enum as a, b and c. We have taken class as program and in the main function we have defined the operators as (+,  -,  ==,  !=, <,  >)  and we have given console.Writeline as (Alphabets.a +25) which prints the value as a value acording to the enum is 0 it increments with the value as 25 and prints the output value as 25. In the nextline we are having the console.Writeline as (45-Alphabets.c) which decrements the 45 value by c. c value means 2 which prints the value as (45-2=43).  In the nextline we are having the console.Writeline  as (Alphabets.a==alphabets.a) which performs the equal operation if the value of a is equal to a it prints the value as true otherwise it prints the value as false. The nextline we are performing the Console.WriteLine (Alphabets.a != Alphabets.a);  If the a value is not equal to a it prints the value as false because a value is equal to a value. The next line we are performing the operation  Console.WriteLine(Alphabets.a < Alphabets.c); this operation performs the value as a greater c it prints the value as true and in the last line we are performing  Console.WriteLine(Alphabets.a > Alphabets.c);  it prints the value as false.

output

 Views: 9352 | Post Order: 15



Write for us






Hosting Recommendations