Reputation: 31
Is it possible to do some thing like this in C#?
class Foo<T> where T : Bar{}
class MyClass<TFoo> where TFoo : Foo<> {}
I don't want to use it like this. in real thing it get 5+ generic parameter
class Foo<T> where T : Bar{}
class MyClass<TFoo, T> where TFoo : Foo<T> {}
Upvotes: 2
Views: 70
Reputation: 8330
When looking at the official documentation, we can see that the languages specification states:
where T: <base class name>
The type argument must be or derive from the specified base class. In a nullable context in C# 8.0 and later, T must be a non-nullable reference type derived from the specified base class.
Example:
public class Foo<T> where T: Bar
{
}
and
where T : U
The type argument supplied for T must be or derive from the argument supplied for U. In a nullable context, if U is a non-nullable reference type, T must be non-nullable reference type. If U is a nullable reference type, T may be either nullable or non-nullable.
Example:
//Type parameter V is used as a type constraint.
public class SampleClass<T, U, V> where T : V { }
And generally, you can't have a generic declaration syntax like this:
public class Foo<T> where T: Bar<> // <> using this syntax is not allowed.
So, the best version for you in the above case could be either:
class Foo<T> where T: Bar{}
class MyClass<TFoo, T> where TFoo : Foo<T> {}
or (as correctly mentioned by @Jon):
class Foo { }
class Foo<T> where T: Bar { }
class MyClass<TFoo> where TFoo : Foo { }
Upvotes: 1