title: How to convert an object to a string with a format string?
body: <p>I have an <code>object</code> which may be boxed from <code>int</code>, <code>float</code>, <code>decimal</code>, <code>DateTime</code>, <code>TimeSpan</code> etc.
  Now I want to convert it to a <code>string</code> with a format string, such as <code>"D4"</code>, <code>"P2"</code>, or <code>"yyyyMMdd"</code>. But the <code>object</code> class doesn't have a <code>ToString</code> method which receives the format string. So the following code doesn't work.</p>
  
  <pre><code>string Format(object value, string format)
  {
      return value.ToString(format); // error
  }
  </code></pre>
  
  <p>Below is my ugly workaround.</p>
  
  <pre><code>string Format(object value, string format)
  {
      if (value is int) return ((int)value).ToString(format);
      if (value is float) return ((float)value).ToString(format);
      if (value is double) return ((double)value).ToString(format);
      if (value is decimal) return ((decimal)value).ToString(format);
      if (value is DateTime) return ((DateTime)value).ToString(format);
      if (value is TimeSpan) return ((TimeSpan)value).ToString(format);
      ...
  }
  </code></pre>
  
  <p>Is there a smarter way?</p>