Why does this generic method require T to have a public, parameterless constructor?

public void GetRecords<T>(ref IList<T> iList, T dataitem)
{
}

What more are you looking for?

To Revised question:

 iList = Populate.GetList<dataItem>() 

“dataitem” is a variable. You want to specify a type there:

 iList = Populate.GetList<T>() 

The type ‘T’ must have a public
parameterless constructor in order to
use it as parameter ‘T’ in the generic
type GetList:new()

This is saying that when you defined Populate.GetList(), you declared it like this:

IList<T> GetList<T>() where T: new() 
{...}

That tells the compiler that GetList can only use types that have a public parameterless constructor. You use T to create a GetList method in GetRecords (T refers to different types here), you have to put the same limitation on it:

public void GetRecords<T>(ref IList<T> iList, T dataitem) where T: new() 
{
   iList = Populate.GetList<T>();
}

Leave a Comment