sclang
sclang

Reputation: 229

Change enum display

How can i have a c# enum that if i chose to string it returns a different string, like in java it can be done by

public enum sample{
    some, other, things;

    public string toString(){
        switch(this){
          case some: return "you choose some";
          default: break;
        }
    }
}

Console.writeln(sample.some) will output:

you choose some

i just want my enums to return a different string when i try to call them.

Upvotes: 10

Views: 1403

Answers (4)

Ben Reich
Ben Reich

Reputation: 16324

To my knowledge this is not possible. However, you can write an extension method that gets some other string:

public static class EnumExtensions
{
    public static string ToSampleString(this SampleEnum enum)
    {
         switch(enum)
         {
             case SampleEnum.Value1 : return "Foo";
             etc.
         }
    }
}

Now, just call this new ToSampleString on instances of SampleEnum:

mySampleEnum.ToSampleString();

If you are unfamiliar with extension methods in C#, read more here.

Another option is to use an Description attribute above each enum value, as described here.

Upvotes: 12

lahsrah
lahsrah

Reputation: 9183

I would do it decoratively by creating an attribute e.g. Description and decorating the enum values with it.

e.g.

public enum Rate
{
   [Description("Flat Rate")]
   Flat,
   [Description("Time and Materials")]
   TM
}

Then use GetCustomAttributes to read/display the values. http://msdn.microsoft.com/en-us/library/system.attribute.getcustomattributes.aspx

@CodeCamper Sorry about the late response but here is some example code to read the DescriptionAttribute:

Extension method:

public static class EnumExtensions
{
    public static string Description<T>(this T t)
    {
        var descriptionAttribute = (DescriptionAttribute) typeof (T).GetMember(t.ToString())
                                   .First().GetCustomAttribute(typeof (DescriptionAttribute));

        return descriptionAttribute == null ? "" : descriptionAttribute.Description;
    }
}

Usage:

Rate currentRate = Rate.TM;
Console.WriteLine(currentRate.Description());

Upvotes: 4

Yemol
Yemol

Reputation: 29

If you just want to get Enum as string you can use this method:

Enum.GetName(typeof(sample), value);

This method will return the name of Enum instead of int.

Upvotes: 0

mcalex
mcalex

Reputation: 6798

You want a dictionary. An enumerator enumerates (gives a number) for its values. You want a string value to be returned when you provide a string key. Try something like:

Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("some", "you choose some");
dictionary.Add("other", "you choose other");
dictionary.Add("things", "you choose things");

Then this code:

string value = dictionary["some"];
Console.writeln(value);

will return "you choose some"

Upvotes: 3

Related Questions