Does anyone know how to make this type of code work?
Type t = typeof(int); // can also be a user designed type
var x= new t(); // won't work!
Same sort of issue: given a MethodInfo, "mi" invoked on an object, the resultant is of type object and must be cast. This works:
int n = (int) mi.Invoke(someobject, null); n has correct value
This does not work:
Type t = typeof(int);
var n = (t) mi.Invoke(someobject, null);
Any idea on how to do this? It works in Delphi but I cannot port the code to C#!
Thanks!
Loading

Sam HobbsRank #107 · 20.5K reputationPosted Dec 18, 2009, 6:49 AM EST
If I knew why that does not work for you then perhaps I could help. Note that if you do that from a function and then return that var item, that won't work as you expect it to.
It will be much better to use the explicit type as in the first example you show.
John3 reputationPosted Dec 18, 2009, 6:59 AM EST
Type t = list[i].Type;
MetodInfo mi = list[i].GetMethod;
var some_value = (t) mi.Invoke(some_object, null);
or, in another instance, something like
Type t = list[i].Type;
if (t is OneOfMyCollectorClasses)
{ t mycollection = new t();}
I have looked at the Activator class, but it too only returns an object. How do I cast this object up to the type it is?
john
Sam HobbsRank #107 · 20.5K reputationPosted Dec 20, 2009, 7:40 PM EST
theLizardRank #1,079 · 1.8K reputationPosted Dec 20, 2009, 9:01 PM EST
if(t.GetType() is (or == ) myObjectType)
myObjectType = new t();
Just an idea!!