title: Cast T parameter in generic method to DateTime
body: <p>I have the following (simplified) method:</p>
  
  <pre><code>private static string GetStringFromValue&lt;T&gt;(T val)
  {
      if (typeof(T) == typeof(DateTime))
      {
          return string.Format("{0}", ((DateTime)val).Year.ToString("0000"));
      }
      return string.Empty;
  }
  </code></pre>
  
  <p>At the cast "(DateTime)val" I get the following error:</p>
  
  <blockquote>
    <p>Cannot cast expression of Type 'T' to type 'DateTime'</p>
  </blockquote>
  
  <p>What can I do to access the Year property of the DateTime parameter?</p>
  
  <p>UPDATE: Thank you for all your very fast answers. This method (and method name) is really (!) simplified to show exactly my problem and to let everyone just copy&amp;paste it into his own visual studio. It is just that I wanted to add some Type specific values if the type is a DateTime. Beside that 99% of the method is the same.</p>