Using default generic values in C#

ado.net c# dapper

Question

I have some code written in C#. I am trying to write some generic code that I can reuse. My actual code is more complicated. However, the code is question looks like the following:

public async Task<T> ExecuteQueryAsync<T>(string sql)
{
  var results = default(T);
  using (var database = new SqlConnection("[ConnectionString]"))
  {
    database.Open();
    results = await database.QueryAsync<T>(sql);                        
  }
  return results;
}

When I build my project, I get a compile-time error that says:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<T>' to 'T'. An explicit conversion exists (are you missing a cast?)

I do not fully understand why I'm getting this error. I intend to call it in a manner like this:

Adapter adapter = new Adapter();
var results = await adapter.ExecuteQueryAsync<IEnumerable<Customer>>("SELECT * FROM Customer");

In the above, wouldn't T be an IEnumerable<T>? If that's the case, I do not understand why I'm getting this type conversion error at compile-time.

Thank you!

Accepted Answer

Try something like this.

public async Task<IEnumerable<T>> ExecuteQueryAsync<T>(string sql)
{
  IEnumerable<T> results = Enumerable.Empty<T>();
  using (var database = new SqlConnection("[ConnectionString]"))
  {
    database.Open();
    results = await database.QueryAsync<T>(sql);                        
  }
  return results;
}

Popular Answer

In your ExecuteQueryAsync you not need it results variable, since you always rewrite it. So your function can be like this

public async Task<IEnumerable<T>> ExecuteQueryAsync<T>(string sql)
{
    using (var database = new SqlConnection("[ConnectionString]"))
    {
        database.Open();
        return await database.QueryAsync<T>(sql);                        
    }
}



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why