C# generics and subclassing - why must I not give the type parameter on ctor? (simple)

Viewed 47

I have

public class LDBList<T> : List<T> where T : LDBRootClass {
    public LDBList<T>(LDBList<T> x) : base(x) { }  // not allowed
    public LDBList   (LDBList<T> x) : base(x) { }  // allowed
    ...
}

Why is the generic type not accepted on the constructor?

1 Answers

The language does not support generic constructors. Have a look at the grammar for constructors:

constructor_declaration
    : attributes? constructor_modifier* constructor_declarator constructor_body
    ;

Compare that with the grammar for methods:

method_declaration
    : method_header method_body
    ;

method_header
    : attributes? method_modifier* 'partial'? return_type member_name type_parameter_list?
      '(' formal_parameter_list? ')' type_parameter_constraints_clause*
    ;

The grammar for methods includes a type_parameter_list, and a type_parameter_constraints_clause, which the grammar for constructors does not.

Even if it did, it is unclear what your code means, because you are declaring a type parameter with the same name as an existing type parameter - the T declared in the class.

Related