Call the generic method using the generic method

It annoys me because I would like to call a generic method from 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, when I call ToList, which is an extension of the DataTable class (found out here )

The compiler says that Y is not a non-abstract type, and it cannot use it for the .ToList <> generic method.

What am I doing wrong?

Thanks for reading..

+6
generics c #
source share
4 answers

Change the method signature to:

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

The reason you need it is because the custom extension method used applies the new() constraint to its generic type argument. This is certainly necessary because it creates instances of this type to populate the returned list.

Obviously, you will also have to call this method with the generic type argument, which is a non-abstract type that has an open constructor without parameters.

+11
source share

It looks like you need:

 public List<Y> GetList<Y>( string aTableName, bool aWithNoChoice) where Y : class, new() { ... } 
+5
source share

It seems that the ToList function has a type restriction:

 where T : new() 

I think that if you use the same restriction for your function (but with Y instead of T ), it should work.

You can read more about this here: http://msdn.microsoft.com/en-us/library/sd2w2ew5(v=VS.80).aspx

+4
source share

I think you need to limit your generic type using the where clause.

+1
source share

All Articles