Wusiji Wusiji - 14 days ago 7
C# Question

Alternative Names for C# enum

In Java, we can declare

enums
like so

public enum ChangeFlag
{
NEW("New"),
DELETED("Deleted"),
REVISED("Revised");

private final String text;

ChangeFlag(String text)
{
this.text = text;
}

public String toString()
{
return text;
}
}


Is there any elegant equivalent to this for C#?

Edit:

public static class FooExtensions
{
public static string GetDescription(this Foo @this)
{
switch (@this)
{
case Foo.Bar:
return "A bar";
}
}


}

Could you explain what the parameters in GetDescription(this Foo @this) mean?
I'm not used to seeing what
this Foo @this
refers to

Answer

You can use DescriptionAttribute:

public enum Foo
{
    [Description("A bar")]
    Bar
}

Which you would then extract via TypeDescriptor.GetAttributes or Type.GetCustomAttributes.

Or you could use extension methods:

public enum Foo
{
    Bar
}

public static class FooExtensions
{
    public static string GetDescription(this Foo @this)
    {
        switch (@this)
        {
            case Foo.Bar:
                return "A bar";
        }
    }
}

// consuming code
var foo = Foo.Bar;
var description = foo.GetDescription();

The latter approach also gives you more control when it comes to localization, since you could always look up the description in a resource file, for example.