Dynamic generic cast at runtime

May 28 2010 4:24 PM
Hello,

I am struggling to try to use generic types when the parameter types are not known until runtime. I can get as far as making an object which contains an instance of the specif type (as below), but it is always an "object" and not the generic type that I wanted. I.e. How can I cast the object to the runtime generic type - or how do I access the member functions of the SortedList<long, string> contained in the object?

Hope the code below makes my question a lot clearer...

Thanks,
Matthew.

           // Make a "Type" called General which is "any kind of SortedList":
            Type General = typeof(SortedList<,>);

            // Make a more specific Type, which is SortedList<long, string>, where we
            // only know that we want <long, string> at runtime:
            Type specific = General.MakeGenericType(new Type[] { typeof(long), typeof(string) });

            // Make an instance:
            ConstructorInfo ci = specific.GetConstructor(new Type[] { });
            object myList = ci.Invoke(new object[] { });

            // Okay, that's great so far. But myList is of type "object" and not
            // SortedList<long, string>. How can I access the methods of the SortedList<long, string>?
            // I can't write:  "myList as SortedList<long, string>" because <long, string> is only known at runtime.
 
            specific wishThisWorkedButItDont = myList as specific;
            wishThisWorkedButItDont.Add(100, "hooray!");


Answers (7)