views:

153

answers:

2

Hi,

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!

+5  A: 

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.

Lucero
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?
theburningmonk
this seems to work by the way, thanks!
theburningmonk
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...
Lucero
+1  A: 

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

LaustN
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!
theburningmonk