hazimdikenli
hazimdikenli

Reputation: 6019

anonymous types and generics

I cannot find a way to pass an anonymous type to a generic class as a type parameter.

// this is the class I want to instantiate

public class ExtArrayStore<T> : IViewComponent 
{
    public IQueryable<T> Data { get; set; }

... // the creator class

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

// trying to use this

IQueryable usersQuery= ((from k in bo.usersselect new { userid = k.userid, k.username}).AsQueryable());
      var x = ArrayStoreGenerator.CreateInstance(usersQuery);

I am getting;

The type arguments for method ArrayStoreGenerator.CreateInstance(System.Linq.IQueryable)' cannot be inferred from the usage. Try specifying the type arguments explicitly

Is there a way to achieve this? ( I am thinking of Interfaces and returning an interface, but not sure if it would work) can any one help with passing anon types to generics.

Upvotes: 5

Views: 1356

Answers (4)

Bryan Watts
Bryan Watts

Reputation: 45445

usersQuery is being typed as the non-generic IQueryable because you explicitly specify that in the variable's declaration.

Instead, do var usersQuery = .... This will type the variable as IQueryable<TAnon>, which then matches the signature of ArrayStoreGenerator.CreateInstance.

Upvotes: 6

Pieter van Ginkel
Pieter van Ginkel

Reputation: 29632

Try with ToArray:

var x = ArrayStoreGenerator.CreateInstance(usersQuery.ToArray());

Upvotes: 0

Andrew Bezzub
Andrew Bezzub

Reputation: 16032

What if you try var usersQuery local variable instead of explicitly specify its type?

Upvotes: 2

Drew Noakes
Drew Noakes

Reputation: 310907

You should define usersQuery as var.

Upvotes: 3

Related Questions