I'm trying to create a generics method. I want the caller to be able to define two different types.
private TableRow AddRowHelper<TROW, TCELL>(params string[] content) where TROW : TableRow where TCELL : TableCell
{
TableRow row = new TROW();
foreach (var text in content)
{
TableCell cell = new TCELL();
cell.Text = text;
row.Cells.Add(cell);
}
productsTable.Rows.Add(row);
return row;
}
The code above gives me an error.
Error 4 Cannot create an instance of the variable type 'TROW' because it does not have the new() constraint"
Is it possible to specify both a new and base-type constraint? And why do I need a new constraint when I have specified that the type must derive from TableRow, which always has a new operator.
Why do I need a new constraint when I have specified that the type must derive from TableRow, which always has a new operator.
Well TROW might be a type that inherits from TableRow and doesn't have a default public constructor.That's why you need to add a new() constraint.
The default, parameterless constructor can be hidden by a deriving class. Hence, the new() constraint can't be inherited from the base class.
Sample:
public class TableRow
{ } // implements a default, parameterless constructor
public class DeivedRow : TableRow
{
public DerivedRow(string s)
{ } // no parameterless constructor
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With