"Bilz" <Br**********@gmail.comwrote in message
news:11**********************@m79g2000cwm.googlegr oups.com...
Ok, lets say I have a generic method:
public T Testing<T>() : where T:class
{
T myT = getStuff() as T;
// Do something with myT
return myT;
}
How do I call it dynamically? The following code does not work, but is
there any way to do it? My understnding of C# generics tells me that I
can... It is not compile-time like C++... I just don't know how.
public object Helper(Type t)
{
return Testing<t>();
}
Help is appreciated :)
Reflection is your friend.
using System;
using System.Collections.Generic;
using System.Reflection;
namespace csTest
{
class Program
{
public static object Helper(Type t)
{
MethodInfo mi = typeof(Program).GetMethod("Testing");
return mi.MakeGenericMethod(t).Invoke(null, null);
}
public static T Testing<T>() where T : class, new()
{
T myT = new T();
// Do something with myT
return myT;
}
class Foo
{
public Foo()
{
}
public override string ToString()
{
return "A Foo";
}
}
static void Main(string[] args)
{
Console.WriteLine(Helper(typeof(Foo)));
Console.ReadKey();
}
}
}
David