Getsuyodev, Programming is mainly used when constructing an application. Programming requires knowledge of application domains, algorithms, and programming language expertise. Programming can be developed in different logic based on developer knowledge.

How to use Enum in C#



If you have several constants that are logically related to each other, then you can group these constants in an enumeration.
Syntax:

Enum declaration :

enum Tempurature
{
  Low,
  Medium,
  High,
};

Enums are strongly typed constants which makes the code more readable and less prone to errors. It is useful when you have a set of values that are functionally significant and unchanged. The main advantage of Enum is to make it easy to change values in the future. Also, you can reduce errors caused by transposing or mistyping numbers.
Retrieve and check the Enum value

Temperature value = Tempurature.Medium;
if (value == Tempurature.Medium)
{
  Console.WriteLine("Temperature is Mediuam..");
}

A simple example

using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        enum Tempurature
        {
            Low,
            Medium,
            High,
        };
        private void button1_Click(object sender, EventArgs e)
        {
            Temperature value = Tempurature.Medium;
            if (value == Tempurature.Medium)
            {
                MessageBox.Show ("Temperature is Mediuam..");
            }
        }
    }
}

By default, the underlying type of each element in the enum is int. If you try with above example to convert to an integer then you can see the result like the following:

Temperature value = Tempurature.Medium;
int val = (int)value;
Console.WriteLine("Temperature value is.." + val);

The output is: Temperature value is..1
You can specify another integral numeric type by using a colon. The following Enum declares as byte; you can verify the underlying numeric values by casting to the underlying type.

enum Temperature : byte
{
    Low,
    Medium,
    High,
};

You can retrieve the value like the following:

Temperature value = Tempurature.Medium;
byte val = (byte)value;
Console.WriteLine("Temperature value is.." + val);

You can assign any values to the elements in the enumerator list of an enumeration type. By default, the first member of an enum takes the value of zero. If this value doesn’t make sense for your Enum, you can change it to one or some other number. If you declare a different value in the first member of Enum then it assigns the next value greater by one than that of the immediately preceding member.

enum Tempurature
{
    Low = 2,
    Medium,
    High,
};
Temperature value = Tempurature.Medium;
int val = (int)value;
Console.WriteLine("Temperature value is.." + val);

The output is: Temperature value is.. 3

How to get int value from enum

enum Days
{
    Sunday = 1,
    TuesDay = 2,
wednesday=3
}
//get value
int day = (int)Days.TuesDay;

How can an int value cast to enum?

Following is the easiest method to cast an int to the enum.

MyEnum myenum = (MyEnum)intvalue;

Ex:

enum Days
{
    Sunday = 1,
    TuesDay = 2,
wednesday=3
}
//cast to enum
Days day = (Days)3;

Converts int to enum values
Method 2:
MyEnum myenum = (MyEnum)Enum.ToObject(typeof(MyEnum) , intvalue);

Days day = (Days)Enum.ToObject(typeof(Days), 3);

You can check if it’s in range using Enum.IsDefined

if (Enum.IsDefined(typeof(Days), day))
{
    MessageBox.Show("Its in tange");
}

Enum.Parse

Enum.Parse() converts the C# string representation of the name or integer value of one or more enumerated constants to an equivalent Enum object.

String convert to Enum

using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public enum Colors
        {
            red,
            blue,
            green,
            yellow
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string inVal = "green";
            Colors newColor = (Colors)Enum.Parse(typeof(Colors), inVal);
            //Check the Enum type
            if (newColor == Colors.green)
            {
                MessageBox.Show(newColor.ToString());
            }
        }
    }
}

The output is: green

How to Loop through all enum values

The C# GetValues method returns an array that contains a value for each member of the enum type. If more than one members have the same value, it returned array includes duplicate values

Iterating through an enum

The following example will show how do enumerate an enum.

using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public enum Colors
        {
            red,
            blue,
            green,
            yellow
        }
        private void button1_Click(object sender, EventArgs e)
        {
            foreach (Colors iColor in Enum.GetValues(typeof(Colors)))
            {
                MessageBox.Show(iColor.ToString());
            }
        }
    }
}
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		enum Tempurature
		{
			Low,
			Medium,
			High,
		};

		private void button1_Click(object sender, EventArgs e)
		{
			Temperature value = Tempurature.Medium;
			switch (value)
			{
				case Tempurature.Low:
					MessageBox.Show("Low Tempurature");
					break;
				case Tempurature.Medium:
					MessageBox.Show("Mediuam Tempurature");
					break;
				case Tempurature.High:
					MessageBox.Show("High Tempurature");
					break;
			}

		}
	}
}

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More