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.
Anonymous types are class types that derive directly from object , and that cannot be cast to any type except object . The compiler provides a name for each anonymous type, although your application cannot access it.
The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.
In C#, an anonymous type is a type (class) without any name that can contain public read-only properties only. It cannot contain other members, such as fields, methods, events, etc. You create an anonymous type using the new operator with an object initializer syntax.
Anonymous type is a class type which gets to known about the type of data at the time of compile only. Declaration of variables of anonymous data type is mandatory otherwise it will raise error. Var keyword is used to represent Anonymous type. After selecting, New Project windows will appear.
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
.
You should define usersQuery as var.
What if you try var usersQuery
local variable instead of explicitly specify its type?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With