title: Convert string to generic type (basic or array) in C#
body: <p>I want to convert a string to a given generic type <code>T</code>. It may be either basic type or string (e.g. <code>int</code> or <code>string</code>), or an array of a basic types or strings (e.g. <code>int[]</code> or <code>string[]</code>). I have the following function:</p>
  
  <pre><code>T Str2Val&lt;T&gt;(string str)
  {
    return (T)Convert.ChangeType(str, typeof(T));
  }
  </code></pre>
  
  <p>It works well for basic types. But it fails for <code>T</code> being an array <code>E[]</code> and <code>str</code> being a comma-separated list of values.</p>
  
  <p>I can easily check whether <code>T</code> is an array with <code>typeof(T).IsArray</code>. Then I have two solutions: parse an array in the same function with a scalar, like the following:</p>
  
  <pre><code>  if (!typeof(T).IsArray)
    {
      return (T)Convert.ChangeType(str, typeof(T));
    }
    else
    {
      // Handle an array
    }
  </code></pre>
  
  <p>or implement two overloaded functions: one for generic <code>T</code> and second for generic <code>E[]</code>. However, both of solutions fail. I cannot use any array-specific code in the else-clause since it must be compatible with a scalar. And C# cannot pick proper overload with <code>E[]</code> when <code>T</code> is actually an array.</p>
  
  <p>What should I do?</p>