I wanted to know if this is possible:
public class Foo<T> where T : Func<T>
or
public class Foo<T> where T : Func<>
It seems like the compiler is telling me it not possible. I suppose I can throw a runtime exception in the constructor, but was hoping to have it a compiler error.
Any ways about doing this?
You can specify one or more constraints on the generic type using the where clause after the generic type name. The following example demonstrates a generic class with a constraint to reference types when instantiating the generic class.
A type constraint on a generic type parameter indicates a requirement that a type must fulfill in order to be accepted as a type argument for that type parameter. (For example, it might have to be a given class type or a subtype of that class type, or it might have to implement a given interface.)
The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function.
Multiple interface constraints can be specified. The constraining interface can also be generic.
Unfortunately, it looks like you are out of luck. Func<>
and Action<>
are both delegate types, which cannot be used as a generic type constraint.
This answer sums it up pretty well C# Generics won't allow Delegate Type Constraints
As the other answer informs, you can't achieve a generic type constraint for Func<>, however C# 7.3 allows you to do a constraint like this
public class Foo<T> where T : Delegate
or
public class Foo<T> where T : MulticastDelegate
that's the closest you can get.
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