A very .NET-ish sort of way would be to use attributes. First, create an
attribute class that can be used to assign a string label to something, such
as an enum value. This is more code than you need for your specific case,
but this is a very general class that can be used to assign a string label
to pretty much anything, for any purpose. Very reusable.
using System;
[AttributeUsage(AttributeTargets.All)]
public class LabelAttribute : Attribute
{
public readonly string Label;
public LabelAttribute(string label)
{
Label = label;
}
public static string FromMember(object o)
{
return ((LabelAttribute)
o.GetType().GetMember(o.ToString())[0].GetCustomAttributes(typeof(LabelAttri
bute), false)[0]).Label;
}
public static string FromType(object o)
{
return ((LabelAttribute)
o.GetType().GetCustomAttributes(typeof(LabelAttribute), false)[0]).Label;
}
}
Then you can use this attribute class to associate a string label with each
of your enum values:
[Label("Comparison operators")]
public enum Comparator
{
[Label("=")]
Equal,
[Label("<")]
LessThan,
[Label("<=")]
LessThanOrEqual,
[Label(">")]
GreaterThan,
[Label(">=")]
GreaterThanOrEqual,
}
And this is how you would read those labels:
Comparator x = Comparator.GreaterThanOrEqual;
string valueLabel = LabelAttribute.FromMember(x);
string typeLabel = LabelAttribute.FromType(x);
John Smith said:
I have a custom enum to list comparison operators: =, <, <=, >, >= . I have
created it as follows:
public enum Comparator {Equal, LessThan,
LessThanOrEqual,GreaterThan,GreaterThanOrEqual}
Now I have to create static functions to convert these enum values to/from
the actual comparison operator strings. As I understand it, I can't add
methods to an enum, so is there any more elegant way to do this?
TIA