tags:

views:

60

answers:

3

Hi All,

I have a generic method in c#:

public IList<T> getList<T>();

When I call it as the way below?

...
Type T1=metadata.ModelType;
getList<T1>();

...

I got error in compiling.

How could I do for it? I really need to pass the type as Variables to the generic method!

+3  A: 

The generic parameter is a type parameter:

getList<string>(); // Return a list of strings
getList<int>(); // Return a list of integers
getList<MyClass>(); // Return a list of MyClass

You are not calling it with a type but with an object.

Oded
Oded, I disagree, it is not called it with an object either. It's only callable when you resolve the generic type first.
Enigmativity
@Enigmativity: what do you mean by that? What do you mean by “resolve”? OP *is* trying to pass an object as a type so you’re wrong.
Konrad Rudolph
@Oded,I don't know the real type before running time, so this is not the way I expected.
Sam Zhou
@"Konrad Rudolph" - He's not passing "an object as a type", he's trying to pass "a type as an object". Normally compile-time type resolution is required. Only using reflection can the type be passed as an object at run-time. I don't know what passing an object as a type would actually mean.
Enigmativity
+2  A: 

As Oded pointed out, you cannot do this the way you tried, since <T> does not accept types. You can, however, achieve what you want using reflection:

Type T1=metadata.ModelType;

MethodInfo method = GetType().GetMethod("getList");
MethodInfo genericMethod = method.MakeGenericMethod(new Type[] { T1 });

genericMethod.Invoke(this, null);

If getList is a static method, or in another class, you need to replace GetType() by typeof(...) with ... being the name of the class.

Jens
@Jens,It's the generic way...
Sam Zhou
A: 

You can't : in your sample, T1 is an instance of the System.Type class and not an actual type like IList for example

Seb
@Seb, Good explainsion...
Sam Zhou