title: Converting Nullable Types Dynamically
body: <p>I'm trying to convert objects dynamically based on a method's parameter object type using this line of code:</p>
  
  <pre><code>Convert.ChangeType(parameter.Value, parameterType);
  </code></pre>
  
  <p>However when <code>parameterType</code> is equivalent to <code>DateTime?</code> or <code>int?</code>, or any other nullable type, this conversion doesn't work. </p>
  
  <p>Why does this conversion not work with nullable types, and is there a way to have it work with nullable types? </p>
  
  <p>(Note: that this is all being done dynamically, so there is no way of knowing beforehand if the type will be nullable or not... unless the <code>Type</code> class has a way of deciphering that and I could then implement some type of <code>if (nullable object) { // do special conversion }</code>?)</p>
  
  <p><em>EDIT:</em></p>
  
  <p>Looking at this question: <a href="https://stackoverflow.com/questions/7313590/how-to-use-convert-changetype-when-conversiontype-is-a-nullable-int">How to use Convert.ChangeType() when conversionType is a nullable int</a></p>
  
  <p>I've tried implementing the following answer:</p>
  
  <pre><code>public static T GetValue&lt;T&gt;(string value)
  {
     Type t = typeof(T);
     t = Nullable.GetUnderlyingType(t) ?? t;
  
     return (value == null || DBNull.Value.Equals(value)) ? 
        default(T) : (T)Convert.ChangeType(value, t);
  } 
  </code></pre>
  
  <p>However this answer is used by doing something like:</p>
  
  <pre><code>string a = 24;
  decimal? d = GetValue&lt;decimal?&gt;(a);
  </code></pre>
  
  <p>But in my case I don't necessarily know it will be of type <code>decimal?</code>; I need to pass in the <code>Type</code> of which I want to convert it to, for example I need to do something like:</p>
  
  <pre><code>Type parameterType = parameterDescriptor.ParameterType;
  var unknownType = GetValue&lt;parameterType&gt;(parameter.Value);
  </code></pre>