I have a string serialization utility that takes a variable of (almost) any type and converts it to a string. Thus, for example, according to my agreement, the integer value 123 will be serialized as "i: 3: 123" (i = integer; 3 = string length; 123 = value).
The utility processes all primitive types, as well as some non-general collections, such as ArrayLists and Hashtables. The interface has the form
public static string StringSerialize(object o) {}
and internally I find out what type of object and serializes it accordingly.
Now I want to update my utility for handling shared collections. The funny thing is that I canβt find a suitable function to detect that the object is a common collection, and what types it contains are both pieces of information that I need to serialize correctly. Today I use form coding
if (o is int) {// do something}
but that doesn't seem to work with generics.
What do you recommend?
EDIT: thanks Lucero , I came closer to the answer, but I was stuck in this little syntax puzzle:
if (t.IsGenericType) { if (typeof(List<>) == t.GetGenericTypeDefinition()) { Type lt = t.GetGenericArguments()[0]; List<lt> x = (List<lt>)o; stringifyList(x); } }
This code does not compile because " lt " is not resolved as the <T> argument of the List<> object. Why not? And what is the correct syntax?
generics c # typechecking
Shaul Behr Apr 16 '09 at 8:20 2009-04-16 08:20
source share