title: Convert string to nullable type (int, double, etc...)
body: <p>I am attempting to do some data conversion. Unfortunately, much of the data is in strings, where it should be int's or double, etc... </p>
  
  <p>So what I've got is something like:</p>
  
  <pre><code>double? amount = Convert.ToDouble(strAmount);
  </code></pre>
  
  <p>The problem with this approach is if strAmount is empty, if it's empty I want it to amount to be null, so when I add it into the database the column will be null. So I ended up writing this:</p>
  
  <pre><code>double? amount = null;
  if(strAmount.Trim().Length&gt;0)
  {
      amount = Convert.ToDouble(strAmount);
  }
  </code></pre>
  
  <p>Now this works fine, but I now have five lines of code instead of one. This makes things a little more difficult to read, especially when I have a large amount of columns to convert.</p>
  
  <p>I thought I'd use an extension to the string class and generic's to pass in the type, this is because it could be a double, or an int, or a long. So I tried this:</p>
  
  <pre><code>public static class GenericExtension
  {
      public static Nullable&lt;T&gt; ConvertToNullable&lt;T&gt;(this string s, T type) where T: struct
      {
          if (s.Trim().Length &gt; 0)
          {
              return (Nullable&lt;T&gt;)s;
          }
          return null;
      }
  }
  </code></pre>
  
  <p>But I get the error: Cannot convert type 'string' to 'T?'</p>
  
  <p>Is there a way around this? I am not very familiar with creating methods using generics.</p>