Naweed Akram's Blog
<sharing: Knowledge />
Descriptive Value for Enums in C#
Posted: August 18, 2010

Consider a scenario that you have the following enum declared, which is used to define SQL operations (keeping it very simple):

    public enum Operands
    {
        Equals,
        GreaterThan,
        LessThan,
        NotEquals
    }

 

Now, if the user wants to convert the enums to values that SQL server can understand (=, <>, <, > etc.), the following needs to be done:

            string _opValue = "";
            Operands _op = Operands.LessThan;

            switch (_op)
            {
                case Operands.Equals:
                    _opValue = "=";
                    break;
                case Operands.GreaterThan:
                    _opValue = ">";
                    break;
                case Operands.LessThan:
                    _opValue = "<";
                    break;
                case Operands.NotEquals:
                    _opValue = "<>";
                    break;
            }

 

Not very convenient. What if, you could say:

            Operands _op = Operands.LessThan;
            Console.Write(_op.ToStringValue());

 

 

It is actually very easy to achieve. We will do it with the help of Attributes and a bit of Reflection.

 

Lets create a simple class derived from Attribute class:

    public class ValueAttribute : Attribute
    {
        public string Value { get; set; }

        public ValueAttribute(string StringValue)
        {
            this.Value = StringValue;
        }
    }

 

Now, let's ammend our Enum class as follows:

    public enum Operands
    {
        [Value("=")]
        Equals,

        [Value(">")]
        GreaterThan,
        
        [Value("<")]
        LessThan,
        
        [Value("<>")]
        NotEquals
    }

 

And create a simple Extention method:

        public static string ToStringValue(this Operands _operand)
        {
            Type _objType = _operand.GetType();

            FieldInfo _fieldInfo = _objType.GetField(_operand.ToString());

            ValueAttribute [] _valueAttributes = _fieldInfo.GetCustomAttributes(typeof(ValueAttribute), false) as ValueAttribute[];

            if (_valueAttributes.Length > 0)
            {
                return _valueAttributes[0].Value;
            }
            
            return null;
        }

 

And we are done. Now you could say (conveniently):

            Operands _op = Operands.LessThan;
            Console.Write(_op.ToStringValue());

Post Comment
 *
Showing all comments

No comments posted
RSS Feed
Newsletter


Quick Links

Tags