title: Custom Attribute For Specifying Display Format
body: <p>Let me start by saying that I don't know that this specifically <em>requires</em> a custom attribute, but the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.aspx" rel="nofollow" title="Display Format Attribute"><code>DisplayFormatAttribute</code></a> most closely matches the intent I am looking for.</p>
  
  <p><hr/>
  <strong>What I Would Like</strong></p>
  
  <p>I would like to be able to specify a string format for properties of a class like so:</p>
  
  <pre><code>public class TestAttribute
  {
      [CustomDisplayFormatAttribute(DataFormatString = "{0}")]
      public int MyInt { get; set; }
  
      [CustomDisplayFormatAttribute(DataFormatString = "{0:0.000}")]
      public float MyFloat { get; set; }
  
      [CustomDisplayFormatAttribute(DataFormatString = "{0:0.0}")]
      public float MyFloat2 { get; set; }
  
      [CustomDisplayFormatAttribute(DataFormatString = "{0:dd/MM/yyyy}")]
      public DateTime MyDateTime { get; set; }
  }
  </code></pre>
  
  <p>...and be able to use it like so:</p>
  
  <pre><code>TestAttribute t = new TestAttribute()
          {
              MyDateTime = DateTime.Now,
              MyFloat = 1.2345678f,
              MyFloat2 = 1.2345678f,
              MyInt = 5
          };
  Console.WriteLine(t.MyDateTime.ToFormattedString());
  Console.WriteLine(t.MyFloat.ToFormattedString());
  Console.WriteLine(t.MyFloat2.ToFormattedString());
  Console.WriteLine(t.MyInt.ToFormattedString());
  </code></pre>
  
  <p><hr/>
  <strong>What I Have Done So Far</strong></p>
  
  <p>I have successfully created the custom attribute <code>CustomDisplayFormatAttribute</code> and have applied it to my elements, however I am unable to get that attribute out without knowledge of my <code>TestAttribute</code> class.</p>
  
  <p>My first thought was to use an extension method to handle it, hence the <code>ToFormattedString()</code> function.</p>
  
  <p>That being said, ideally I would be able to call a function like <code>ToFormattedString()</code> and have it handle looking up the display format and applying the value to it.</p>
  
  <p><hr/>
  <strong>My Questions</strong></p>
  
  <ol>
  <li>Is this possible using C#</li>
  <li>How can I get this (or similar) functionality.</li>
  </ol>