Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to Create Instance of Generics Type

Tags:

c#

generics

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.

like image 228
Jonathan Wood Avatar asked Mar 29 '26 21:03

Jonathan Wood


2 Answers

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.

like image 173
Selman Genç Avatar answered Apr 02 '26 03:04

Selman Genç


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
}
like image 43
Patrick Hofman Avatar answered Apr 02 '26 04:04

Patrick Hofman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!