title: .NET reflection: determining whether an array of T would be convertible to some other type
body: <p>Note, this question is a bit subtle so read it carefully: I'm not just trying to find out whether some artibitrary type implements IEnumerable:</p>
  
  <p>Here's a function I've written with an initial implementation:</p>
  
  <pre><code>    // is "toType" some sort of sequence that would be satisfied
      // by an array of type T? If so, what is the type of T?
      // e.g.
      // getArrayType(typeof(string[]) == typeof(string)
      // getArrayType(typeof(IEnumerable&lt;int&gt;)) == typeof(int)
      // getArrayType(typeof(List&lt;string&gt;)) == null // NOTE - Array&lt;string&gt; does not convert to List&lt;string&gt;
      // etc.
      private static Type getArrayType(Type toType)
      {
          if (toType.IsArray)
          {
              if (toType.GetArrayRank() != 1)
                  return null;
              return toType.GetElementType();
          }
          // Look for IEnumerable&lt;T&gt;, and if so, return the type of T
          if (toType.IsGenericType &amp;&amp; toType.GetGenericTypeDefinition() == typeof(IEnumerable&lt;&gt;))
              return toType.GetGenericArguments()[0];
  
          return null;
      }
  </code></pre>
  
  <p>Can it be better and handle more cases? e.g. currently</p>
  
  <pre><code>getType(typeof(ICollection&lt;string&gt;)) == null 
  </code></pre>
  
  <p>but string[] is convertible to ICollection</p>
  
  <p>Note also, I don't know in advance what the "element" type is.</p>
  
  <p>The context is: I'm writing a reflection binding to a scripting language and I want it to "just work" if you pass an object[] to some method that expects IEnumerable (it would convert each of the elements of the input array to a string, in this case).</p>
  
  <p>So to clarify, say I have some method signature:</p>
  
  <pre><code>void WriteCSV(ICollection&lt;string&gt; fields);
  </code></pre>
  
  <p>and my script interpreter has an array of objects that all happen to be Convert-ible to string:</p>
  
  <pre><code>object[] fields = new object[] { "one", 2, "three" };
  </code></pre>
  
  <p>Then my script interpreter needs to figure out that what's really needed in this case is an array of strings.</p>
  
  <p>Whereas I want my script interpreter to give up on, say:</p>
  
  <pre><code>void WriteCSV(IRecord record);
  </code></pre>
  
  <p><em>even though</em> IRecord might even implement some IEnumerable:</p>
  
  <pre><code>interface IRecord : IEnumerable&lt;string&gt;
  {
      void OtherMethods();
  }
  </code></pre>
  
  <p>There's no way I can construct an IRecord from an array of anything.</p>
  
  <p>So just finding out what IEnumerables a type implements isn't what I need. I <em>said</em> it was subtle didn't I?</p>