Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a generic method with a generic method

Tags:

c#

generics

I am annoyed because I would like to call a generic method from a another generic method..

Here is my code:

public List<Y> GetList<Y>(
                string aTableName,
                bool aWithNoChoice)
{
  this.TableName = aTableName;
  this.WithNoChoice = aWithNoChoice;

  DataTable dt = ReturnResults.ReturnDataTable("spp_GetSpecificParametersList", this);

  //extension de la classe datatable
  List<Y> resultList = (List<Y>)dt.ToList<Y>();

  return resultList;  
}

So in fact when I call ToList who is an extension to DataTable class (learned Here)

The compiler says that Y is not a non-abstract Type and he can't use it for .ToList<> generic method..

What am I doing wrong?

Thanks for reading..

like image 462
bAN Avatar asked Dec 01 '10 10:12

bAN


1 Answers

Change the method signature to:

public List<Y> GetList<Y>(
                string aTableName,
                bool aWithNoChoice) where Y: new()

The reason you need that is because the custom extension-method you use imposes the new() constraint on its generic type argument. It certainly needs to, since it creates instances of this type to populate the returned list.

Obviously, you will also have to call this method with a generic type argument that represents a non-abstract type that has a public parameterless constructor.

like image 177
Ani Avatar answered Sep 28 '22 07:09

Ani