views:

1642

answers:

1

Hi,

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.

+6  A: 

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.

Jon Skeet
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 :(
SharePoint Newbie
Thanks Jared. That's the problem with writing code on the steps of a train station :)
Jon Skeet
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.
SharePoint Newbie
Editing my answer to explain...
Jon Skeet