Weholt
Weholt

Reputation: 1989

Using generics to produce a IEnumerable for generic type

I've got a class X, Y and Z and need a way to have one method to return an IEnumerable of X, Y or Z, something like :

public IEnumerable<T> BuildList<T>(String sql)
{
    return Query<T>(sql);
}

Where Query is a custom method to do SQL queries and mapping the result to a IEnumerable of T.

I want to use it like :

var x_items = BuildList<X>("select * from table_x");
var y_items = BuildList<Y>("select * from table_y");
var z_items = BuildList<Z>("select * from table_z");

Is the problem the Query-method or I'm I just doing the generics wrong?

Upvotes: 1

Views: 1049

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503729

Given the compiler error you've given in the comment, it sounds like you just need a type constraint on T:

public IEnumerable<T> BuildList<T>(String sql) where T : class, new()
{
    return Query<T>(sql);
}

Upvotes: 4

DeveloperX
DeveloperX

Reputation: 4683

type of T should be exist in dbcontext

Upvotes: 1

Related Questions