Dynamically call a generic?

B

Bilz

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 :)
 
D

David Browne

Bilz said:
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
 
B

Bilz

David said:
Bilz said:
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

Thanks! I had thought about reflection, but was hoping there might be
a quicker way.

B
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top