Reputation: 53257
I want to constraint a template type to specific subclass, which is done like this:
// This class contains generic list template
// but specific implementation can be used
class MyClass<T> where T: IEnumerable {}
But I also want to implement a class, without template, that's:
class MyClass: MyClassBase {}
But how do I combine those two things? This is an error:
class MyClass<T> where T: IEnumerable : MyClassBase {}
Also error:
class MyClass<T> where T: IEnumerable, : MyClassBase {}
Error:
class MyClass<T> (where T: IEnumerable) : MyClassBase {}
Error:
class MyClass<T where T: IEnumerable>: MyClassBase {}
What's the correct syntax? MSDN doesn't bother explaining it.
Upvotes: 0
Views: 260
Reputation: 726899
The correct syntax is to specify inheritance first, and then add where
:
class MyClass<T> : MyClassBase where T: IEnumerable {
}
Here is the corresponding C# grammar specifying that class_base
comes ahead of type_parameter_constraints_clauses
:
class_declaration ::= attributes? class_modifiers? partial? class identifier type_parameter_list? class_base? type_parameter_constraints_clauses? class_body ;?
Upvotes: 4
Reputation: 1196
private class BaseClass { }
private class MyClass<T> : BaseClass
where T : IEnumerable
{
}
Upvotes: 0