6

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..

Community
  • 1
  • 1
bAN
  • 13,375
  • 16
  • 60
  • 93
  • Maybe start with compilable code? I assume it should be `dt.AsEnumerable().ToList()` – H H Dec 01 '10 at 10:41
  • 1
    @Henk Holterman: The OP appears to be using a custom extension-method, not the LINQ to Objects `Enumerable.ToList` method. – Ani Dec 01 '10 at 10:45
  • @Ani: I guess so, but that would be something to mention. – H H Dec 01 '10 at 20:52
  • @Henk Holterman "..I call ToList who is an extension to DataTable class (learned Here)" This is the mention.. – bAN Dec 30 '10 at 12:16

4 Answers4

11

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.

Ani
  • 111,048
  • 26
  • 262
  • 307
5

It sounds like you need:

public List<Y> GetList<Y>(
     string aTableName,
     bool aWithNoChoice) where Y : class, new()
{ ... }
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 2
    what is difference between WHERE Y : new() and where Y: class, new()? Thanks for response! – bAN Dec 01 '10 at 10:41
  • 2
    @bAN - `where Y : class` ensures that `Y` is a *reference type* (most likely, a `class`). Actually you might not need this - re-reading the linked `ToList` it just needs `where Y : new()`, so @Ani's answer is correct. – Marc Gravell Dec 01 '10 at 10:53
4

It looks like the ToList function has a constraint on the type:

where T : new()

I think that if you use that same constraint on your function (but with Y instead of T) it should work.

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

Jordi
  • 5,846
  • 10
  • 40
  • 41
1

I guess you need to constraints on your generic type by using where clause.

Shekhar
  • 11,438
  • 36
  • 130
  • 186