Mark Chidlow
Mark Chidlow

Reputation: 1472

How do I declare a generic async Task?

I have the following method:

public async Task<List<Product>> GetProductsAsync()

Which is fine, returns a list of Products.

However I'd like to make this generic - something like...

public async Task<List<T>> GetAsync()

But I'm struggling with syntax and I'd really appreciate it if someone can point me in the right direction.

Thanks

Upvotes: 12

Views: 14185

Answers (2)

usr
usr

Reputation: 171246

Almost there:

public async Task<List<T>> GetAsync<T>()

Upvotes: 18

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

Creating generic method that returns a task is not different from creating a generic method returning anything else:

public async Task<List<T>> GetStuffAsync<T>() {
    ...
}

You need to provide a generic type parameter T to make the syntax work. Generally, though you would probably want something else to generate that list inside the method, for example

public async Task<List<T>> GetStuffAsync<T>(Func<T> gen) {
    ...
}

Upvotes: 4

Related Questions