title: How do I detect that an object is a generic collection, and what types it contains?
body: <p>I have a string serialization utility that takes a variable of (almost) any type and converts it into a string.  Thus, for example, according to my convention, an integer value of 123 would be serialized as "i:3:123" (i=integer; 3=length of string; 123=value).</p>
  
  <p>The utility handles all primitive type, as well as some non-generic collections, like ArrayLists and Hashtables.  The interface is of the form</p>
  
  <p><code>public static string StringSerialize(object o) {}</code></p>
  
  <p>and internally I detect what type the object is and serialize it accordingly.</p>
  
  <p>Now I want to upgrade my utility to handle generic collections.  The funny thing is, I can't find an appropriate function to detect that the object is a generic collection, and what types it contains - both of which pieces of information I need in order to serialize it correctly.  To date I've been using coding of the form </p>
  
  <p><code>if (o is int) {// do something}</code></p>
  
  <p>but that doesn't seem to work with generics.</p>
  
  <p>What do you recommend?</p>
  
  <hr>
  
  <p>EDIT: Thanks to <a href="https://stackoverflow.com/questions/755200/how-do-i-detect-that-an-object-is-a-generic-collection-and-what-types-it-contain/755217#755217">Lucero</a>, I've gotten closer to the answer, but I'm stuck at this little syntactical conundrum here:</p>
  
  <pre><code>if (t.IsGenericType) {
    if (typeof(List&lt;&gt;) == t.GetGenericTypeDefinition()) {
      Type lt = t.GetGenericArguments()[0];
      List&lt;lt&gt; x = (List&lt;lt&gt;)o;
      stringifyList(x);
    }
  }
  </code></pre>
  
  <p>This code doesn't compile, because "<code>lt</code>" is not allowed as the <code>&lt;T&gt;</code> argument of a <code>List&lt;&gt;</code> object.  Why not?  And what is the correct syntax?</p>