Search This Blog

Friday, May 25, 2012

C# Emumeration with custom ToString method



When using Enum in any language you want to have a method to pretty print them. A very easy way to accomplish this in C# is with extension methods.
Here is a quick example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RickysGuitars
{
    public enum GuitarType
    {
        ACOUSTIC,
        ELECTRIC
    }

    public static class GuitarTypeExtentions
    {
        public static string ToPrettyString(this GuitarType source)
        {
            switch (source)
            {
                case GuitarType.ACOUSTIC:
                    return "Acoustic Guitar";
                case GuitarType.ELECTRIC:
                    return "Electric Guitar";
            }
            return null;
        }

    }

    
}


An example of the method call would be

GuitarType a = GuitarType.ELECTRIC;
            Debug.WriteLine(a.ToPrettyString());

which prints: Electric Guitar



No comments:

Post a Comment