Tuesday, 14 December 2010

How to use Switch Statement with Enum in C#

This sample code will help you to implement switch statements using the enums. This is good practice as sometimes you can not remember exact switch option and misspelled. So always use enums if want to hardcode some values.

How to use Switch Statement with Enum in C#

Code:

using System;
using System.Collections.Generic;

namespace MyApp
{  
    public enum Number
    {
        one,
        two,
        three
    }
    class Program
    {
        static void Main(string[] args)
        {  
            Number enum_variable = Number.two;

            switch (enum_variable)
            {
                case Number.one:
                    Console.WriteLine("The Selected Number is one.");
                    break;
                case Number.two:
                    Console.WriteLine("The Selected Number is two.");
                    break;
                case Number.three:
                    Console.WriteLine("The Selected Number is three.");
                    break;
            }
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment