Search code examples
c#genericsgeneric-programming

Getting 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method


I'm kinda new to C#, and i've seen a few examples on how to do generic handling, but i couldn't find an example in layman's terms

I'll share as to what im trying to do, please any inputs in simple language would be deeply appreciated

static readonly Lazy<SQLiteAsyncConnection> lazyInitializer = new Lazy<SQLiteAsyncConnection>(() =>
    {
        return new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags);
    });

    public static SQLiteAsyncConnection Database => lazyInitializer.Value;

    public async Task<List<T>> GetItemsAsync<T>()
    {
        var data = await Database.Table<T>().ToListAsync();
        return data;
        //return Database.Table<TodoItem>().ToListAsync();
    }

I'm getting an error as

'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'SQLiteAsyncConnection.Table<T>()'

I've been going through this Generic in C#, but i'm having a hard time making sense


Solution

  • There is a generic type constraint on the type parameter of Table<T>. You have to ensure then, that any new generic type parameter you introduce that you want to use with Table<T> has a matching (or stricter) type constraint. Here, it's the new() constraint:

    public async Task<List<T>> GetItemsAsync<T>() where T: new()
    {
        var data = await Database.Table<T>().ToListAsync();
        return data;
        //return Database.Table<TodoItem>().ToListAsync();
    }