13

I have a class ReportingComponent<T>, which has the constructor:

public ReportingComponent(IQueryable<T> query) {}

I have Linq Query against the Northwind Database,

var query = context.Order_Details.Select(a => new 
{ 
    a.OrderID, 
    a.Product.ProductName,
    a.Order.OrderDate
});

Query is of type IQueryable<a'>, where a' is an anonymous type.

I want to pass query to ReportingComponent to create a new instance.

What is the best way to do this?

Kind regards.

1 Answer 1

19

Write a generic method and use type inference. I often find this works well if you create a static nongeneric class with the same name as the generic one:

public static class ReportingComponent
{
  public static ReportingComponent<T> CreateInstance<T> (IQueryable<T> query)
  {
    return new ReportingComponent<T>(query);
  }
}

Then in your other code you can call:

var report = ReportingComponent.CreateInstance(query);

EDIT: The reason we need a non-generic type is that type inference only occurs for generic methods - i.e. a method which introduces a new type parameter. We can't put that in the generic type, as we'd still have to be able to specify the generic type in order to call the method, which defeats the whole point :)

I have a blog post which goes into more details.

Sign up to request clarification or add additional context in comments.

6 Comments

On trying to compile I get the error: The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) Seems it still cannot infer the type of T :(
Thanks Jared. That's the problem with writing code on the steps of a train station :)
One question, why do we need the non-generic class? Why doesn't it work with the generic class only? Type Inference should still work.
I find it strange that a new() clause on the original generic class prevents this approach, but so it does....
@MPelletier: I'm not sure what you mean. It really shouldn't... perhaps ask a new question about that, with an example?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.