Wednesday, 20 March 2019

.net - Passing arguments to C# generic new() of templated type



I'm trying to create a new object of type T via its constructor when adding to the list.




I'm getting a compile error: The error message is:




'T': cannot provide arguments when creating an instance of a variable




But my classes do have a constructor argument! How can I make this work?



public static string GetAllItems(...) where T : new()
{

...
List tabListItems = new List();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(new T(listItem)); // error here.
}
...
}

Answer




In order to create an instance of a generic type in a function you must constrain it with the "new" flag.



public static string GetAllItems(...) where T : new()


However that will only work when you want to call the constructor which has no parameters. Not the case here. Instead you'll have to provide another parameter which allows for the creation of object based on parameters. The easiest is a function.



public static string GetAllItems(..., Func del) {
...
List tabListItems = new List();

foreach (ListItem listItem in listCollection)
{
tabListItems.Add(del(listItem));
}
...
}


You can then call it like so




GetAllItems(..., l => new Foo(l));

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...