Mr.Sheep
Mr.Sheep

Reputation: 311

Use T as a type

I have a sqlite class with a few entities and I don't want to create a method for every type of entity like this:

public async List<Sheep> GetSheeps()
{
    return database.Table<Sheep>().ToListAsync();
}

public async List<Goat> GetGoats()
{
    return database.Table<Goat>().ToListAsync();
}

I want to create an interface (e.g. IEntity) and inherit it my POCO classes of sheep and goat. Then I want to create just one generic method to get the items.

This is what I tried, it says I cannot use T as a type:

public async T GetEntities<T>()
{
    if (typeof(T) == IEntity)
        return database.Table<T>().ToListAsync();
}

Maybe I dind't completely understand what T is..

Any help appreciated.

Upvotes: 0

Views: 100

Answers (1)

TheGeneral
TheGeneral

Reputation: 81583

Nearly...

  • You will want to await an async call
  • Since you are using an async await pattern, you will need to return a Task
  • Since you want to return a list of T you will have to declare the List<T> as a generic parameter of your task i.e Task<List<T>>
  • Instead of checking for the type typeof(T) == IEntity use a constraint where T : IEntity

Code

public async Task<List<T>> GetEntities<T>() where T : IEntity
{
    return await database.Table<T>().ToListAsync();
}

Though, some things to consider

  • All your classes will have to inherit from IEntity
  • It's best to use the using statement when dealing with a db (and not hold a reference to it)
  • This smells like a repository and you are not really saving much code. EF and ORMS are already a repository pattern and unit of work

Using

var myLovelyHorseList = await GetEntities<Horse>();

Update

Its a bit early in the morning for me and i am with out a coffee and cant test this. but i think you might need the new() constraint, and your classes will have to have a parametesless constructor

where T : IEntity, new()

new Constraint (C# Reference)

Upvotes: 3

Related Questions