public enum ProjectPhase
{
RequirementsGathering = 1,
AnalysisDesign = 2,
}
In the above example we need to display more meaningful values on screen. This can be achieved by using the System.ComponentModel and System.Reflection namespace.
{
RequirementsGathering = 1,
AnalysisDesign = 2,
}
Step 1: Use the DescriptionAttribute class to provide the friendly name for enum values.
using System.ComponentModel;
public enum ProjectPhase
{
[Description("Requirements Gathering")]
RequirementsGathering = 1,
[Description("Analysis and Design")]
AnalysisDesign = 1,
}
public enum ProjectPhase
{
[Description("Requirements Gathering")]
RequirementsGathering = 1,
[Description("Analysis and Design")]
AnalysisDesign = 1,
}
Step 2: Create an static class which contains an extension method that extends the Enum type. This extension method GetDecription returns the description of the provided enum value. If there is no description attribute applied on the enum value then the string representation of the enum value is returned.
public static class EnumExtensions
{
public static string GetDescription(this Enum value)
{
string description = string.Empty;
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
description = attributes[0].Description;
else
description = value.ToString();
return description;
}
}
{
public static string GetDescription(this Enum value)
{
string description = string.Empty;
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
description = attributes[0].Description;
else
description = value.ToString();
return description;
}
}
Step 3: Accessing the Description of enum value
Console.WriteLine(ProjectPhase.Code.GetDescription());
No comments:
Post a Comment