Enums to make your code easily understandable

Posted: August 26, 2013 in .Net
Tags: , , ,

It’s been quite some time since I shared anything and today I am going to share something about Enums. When you use Enums, it makes your code easily understandable.

Lets take a small Enum as example

public enum Status

        {

            New = 1,

            Active = 2,

            Inactive = 3

        }

  If you want to change an Enum into array of strings, you can use the Enum class GetNames method:

string[] Status = Enum.GetNames(typeof(Status));

You can bind the output from GetNames to a control to get the list of the names in the Enum displayed in UI.

There is a common scenario where we want to convert  a string containing one of the names in an Enum into the Enum item itself when you are reading the data from database.

Parse method below does that job,but throws an exception “System.ArgumentException was unhandled” if the string value you are passing to Parse isn’t an item in the Enum.

string custStatus = “Test”;

Status sts = (Status)Enum.Parse(typeof(Status), custStatus);

This exception can be avoided if you use the Enum’s TryParse method.

  Status stat;

    if (Enum.TryParse<Status>(custStatus, true, out stat))

    {

        Console.WriteLine(“Status Found: “+stat.ToString());

    }

    else

    {

        Console.WriteLine(“Status not found!”);

    }

An even better solution  is to use the Enum’s IsDefined method to see if the item exists before you try to get it .

if (Enum.IsDefined(typeof(Status), custStatus))

            {

                Status sts = (Status)Enum.Parse(typeof(Status), custStatus);

            }

            else

            {

                Console.WriteLine(“Status not found!”);

            }

 

Hope you enjoyed reading this.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s