Posts Tagged ‘Enum System.ArgumentException’

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