Skip to content
halcharger edited this page Apr 2, 2014 · 2 revisions

#####Enums.GetDescription

In many instances we want to display a friendly name for an enum value. For example given the following enum:

public enum Status
{
	Pending
	RunFailed
	RunSucceeded
}

When displaying these enum values in a UI we ideally would want to display the values "Run Failed" instead of "RunFailed" and so on. We can apply the System.ComponentModel.DescriptionAttribute like this:

public enum Status
{
	Pending
	[Description("Run Failed")]
	RunFailed
	[Description("Run Suceeded")]
	RunSucceeded
}

And then access the descriptive text of an enum value like this:

Status.Pending.GetDescription() == "Pending"

Status.RunFailed.GetDescription() == "Run Failed"

Status.RunSucceeded.GetDescription() == "Run Succeeded"

You'll notice that when a DescriptionAttribute is not applied the standard enum ToString value is returned.

#####Enums.GetValues

In order to get a list of enum values for display in the UI or comparision we can write:

var enumValues = Enums.GetValues<Status>().ToList();

enumValues[0] == Status.Pending
enumValues[1] == Status.RunFailed
enumValues[2] == Status.RunSucceeded

If you don't like using the above syntax you can also write the following:

var enumValues = typeof(Status).GetValues<Status>();

Personally it's not my favourite syntax but it's there if you want to use it.

#####Enums.ToEnum

Given the string value of an enum we can quickly convert this back to the enum value by writing the following:

"Pending".ToEnum<Status>() == Status.Pending;

You can also use the string description value of an enum value, like this:

"Run Failed".ToEnum<Status>() == Status.RunFailed;
Clone this wiki locally