views:

63

answers:

4

I have this common code:

private bool DoItStartup(IReader reader, Type provider)
{
 /// lots of common boiler plate code
 /// like:

    var abcProvider = reader.ReaderData as AbcProvider;
    var xyzProvider = abcProvider.Provisions.FirstOrDefault<XyzProvider>(); // line 2
}

The above lines of code are there for like 50 or some providers, now Line 2 I want to basically do this:

var xyzProvider = abcProvider.Provisions.FirstOrDefault<typeOf(provider)>();

This doesn't work, possibly because xyzProvider doesn't know it's type @ compile time? Not sure. But is there a similar pattern I can use. Otherwise I'm having to duplicate this cruft code 50 times :(

+3  A: 

Without knowing the type of abcProvider.Provisions it's a bit hard to say for sure... but normally I don't provide any type arguments to FirstOrDefault... I just let type inference work.

Have you tried just calling:

var xyzProvider = abcProvider.Provisions.FirstOrDefault();

?

(The reason it's not working is that type arguments have to be names of types or type parameters; they can't be expressions computed at execution time.)

Jon Skeet
I was wondering why this wouldn't work actually. (If it, in fact, won't work for what he needs)If this doesn't work then having an overall interface for the providers might be the better solution. But I'd for sure want to start here.
Rangoric
+1  A: 

It sounds like you need to provide a generic parameter to either the method or the class that encloses the code above. The following should work properly (not sure how provider is being passed in

public T GetStuff() {
   var xyzProvider = abcProvider.Provisions.FirstOrDefault<T>();
}
Ryan Brunner
+1  A: 

You might need to use Generics.

There are several articles on the MSDN that cover this:

Generics (C# Programming Guide)

An Introduction to C# Generics

Generic Methods (C# Programming Guide)

ChrisF
A: 

Generic parameters of generic types are determined at compile type (not run time). But you want your code to get type of FirstOrDefault at runtime which causes the error.
Try using this instead:
private bool DoItStartup<T>(IReader reader, Type provider) {
...
var x=list.FirstOrDefault<T>();
}

Sepidar