CopyPastehas never been so tasty!

Using switch statement with enum in c#

by anonymous

  • 0
  • 0
  • 0
109 views

Using switch statement with enum in c#

Switch StatementThe switch statement is just like a set of if statements. It is a list of possibilities of a program, each with a specific action to perform and if nothing else evaluates to true then the default action will be shown.  A simple switch statement is of the form: int number = 1; 

switch(number)

{

case 0:

Console.WriteLine("The number is zero!");

break;

case 1:

Console.WriteLine("The number is one!");

break;

}

ENUM keywordWe use the enum keyword to declare an enumeration. The default type of each element in the enum is int.EnumerationEnumeration provides the best way to define a set of named integral constants which we assigned to a variable by using the enum keyword before variable. For an instance, if we define a variable whose value will represent the name of the countries then we can declare enumeration in this wayEnum CountryNames {Pakistan, Japan, Italy, Spain};

 Using switch statement with enum In the following code, the enum is of type Volume and the type of each element in the enum is Byte. We use it to declare the myVolume variable in the Main method. We can directly assign a value like (Volume.Medium) and can use it in switch statement.Code 

using System;

class EnumSwitch

    {

           public enum Volume :byte

        {

            Low =20,

            Medium =24,

High  =33

        }

static void Main(string[] args)

        {

             Volume myVolume;

myVolume = Volume.Medium;

EnumSwitch.PureVolume(myVolume);

Console.WriteLine(myVolume.ToString());

  }

 public static void PureVolume(Volume myVolume)

        {

switch (myVolume)

            {

case Volume.Low:

Console.WriteLine("The Volume is Low");

break;

case Volume.Medium:

Console.WriteLine("The Volume is in the Middle");

break;

case Volume.High:

Console.WriteLine("The Volume is High");

break;

            }

Console.ReadLine();

        }

    }

 }

Add A Comment: