title: Casting an object to IEnumerable<T> where T is not known
body: <p>I am trying to play with Reflection and ran into the following situation. </p>
  
  <p>In the following code, let's assume that the 'obj' can be of types <code>IEnumerable&lt;&gt;</code> or <code>ICollection&lt;&gt;</code> or <code>IList&lt;&gt;</code>. </p>
  
  <p>I would like to cast this System.Object to <code>IEnumerable&lt;&gt;</code> always (as <code>ICollection&lt;&gt;</code> and <code>IList&lt;&gt;</code> inherit from <code>IEnumerable&lt;&gt;</code> anyway), so that i would like to enumerate over the collection and use reflection to write the individual items.</p>
  
  <p>Motivation behind this is I am just trying to see if how would Serializers, in general, serialize data and so I am trying to simulate that situation in the hope to understand Reflection too.</p>
  
  <p>I thought of casting the object to <strong>non-generic IEnumerable</strong>, but thought that this would cause unnecessary boxing of objects, when let's say the actual instance of <code>IEnumerable&lt;int&gt;</code>...am I thinking right?</p>
  
  <pre><code>private void WriteGenericCollection(object obj)
      {
          Type innerType = obj.GetType().GetGenericArguments()[0];
  
          //Example: IEnumerable&lt;int&gt; or IEnumerable&lt;Customer&gt;
          Type generatedType = typeof(IEnumerable&lt;&gt;).MakeGenericType(innerType);
  
          //how could i enumerate over the individual items?
      }
  </code></pre>