Can I pass a type object to a generic method? [duplicate]
Asked Answered
K

2

15

I have a FindAll method on my DataAccessLayer which looks like this:

public FindResult<T> FindAll<T>() where T : Entity, new()

and a client code that has a Type[] array which it needs to use to iteratively call the FindAll method with like this:

foreach (var type in typeArray)
{    
    var result = DataAccessLayer.FindAll<type>();
    ...

but the compiler complaints about "Type or namespace expected".. Is there an easy way to get around this? I've tried type.GetType() or typeof(type) and neither worked.

Many thanks in advance!

Kedge answered 20/1, 2010 at 10:53 Comment(0)
M
13

You may need to use Reflection to do this, something like this:

DataAccessLayer.GetType().GetMethod("FindAll<>").MakeGenericMethod(type).Invoke()

This blog post may also contain the information you need.

Match answered 20/1, 2010 at 10:59 Comment(2)
Is it because C# doesn't support dynamic typing (I heard it's supported in C# 4.0) that my original code didn't work?Kedge
I'm not sure if the dynamic support in C# 4 would allow you to do this in a different way, since I don't know how you could supply the dynamic generic type there either. But I haven't tried it...Match
A
3

When using generics, the type needs to be resolveable at compile time. You are trying to supply the type at runtime.

Asia answered 20/1, 2010 at 11:19 Comment(1)
yeah, I realised that now, I was trying to use dynamic typing which is not supported at the moment, but reading on .Net 4.0, C# is going to introduce support for dynamic typing so maybe what I was trying to do will be possible in the near future!Kedge

© 2022 - 2024 — McMap. All rights reserved.