title: String representation of an Enum
body: <p>I have the following enumeration:</p>
  
  <pre><code>public enum AuthenticationMethod
  {
      FORMS = 1,
      WINDOWSAUTHENTICATION = 2,
      SINGLESIGNON = 3
  }
  </code></pre>
  
  <p>The problem however is that I need the word "FORMS" when I ask for AuthenticationMethod.FORMS and not the id 1.</p>
  
  <p>I have found the following solution for this problem (<a href="http://www.codeproject.com/Articles/11130/String-Enumerations-in-C" rel="noreferrer">link</a>):</p>
  
  <p>First I need to create a custom attribute called "StringValue":</p>
  
  <pre><code>public class StringValue : System.Attribute
  {
      private readonly string _value;
  
      public StringValue(string value)
      {
          _value = value;
      }
  
      public string Value
      {
          get { return _value; }
      }
  
  }
  </code></pre>
  
  <p>Then I can add this attribute to my enumerator:</p>
  
  <pre><code>public enum AuthenticationMethod
  {
      [StringValue("FORMS")]
      FORMS = 1,
      [StringValue("WINDOWS")]
      WINDOWSAUTHENTICATION = 2,
      [StringValue("SSO")]
      SINGLESIGNON = 3
  }
  </code></pre>
  
  <p>And of course I need something to retrieve that StringValue:</p>
  
  <pre><code>public static class StringEnum
  {
      public static string GetStringValue(Enum value)
      {
          string output = null;
          Type type = value.GetType();
  
          //Check first in our cached results...
  
          //Look for our 'StringValueAttribute' 
  
          //in the field's custom attributes
  
          FieldInfo fi = type.GetField(value.ToString());
          StringValue[] attrs =
             fi.GetCustomAttributes(typeof(StringValue),
                                     false) as StringValue[];
          if (attrs.Length &gt; 0)
          {
              output = attrs[0].Value;
          }
  
          return output;
      }
  }
  </code></pre>
  
  <p>Good now I've got the tools to get a string value for an enumerator.
  I can then use it like this:</p>
  
  <pre><code>string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);
  </code></pre>
  
  <p>Okay now all of these work like a charm but I find it a whole lot of work. I was wondering if there is a better solution for this.</p>
  
  <p>I also tried something with a dictionary and static properties but that wasn't better either.</p>