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
theLizardPosted Dec 21, 2009, 2:01 AM
if(t.GetType() is (or == ) myObjectType)
myObjectType = new t();
Just an idea!!
Sam HobbsPosted Dec 21, 2009, 12:40 AM
JohnPosted Dec 18, 2009, 11:59 AM
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 HobbsPosted Dec 18, 2009, 11:49 AM
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.