Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a generic type constraint on Func<T>

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?

like image 693
halivingston Avatar asked Oct 04 '14 22:10

halivingston


People also ask

How do you add a generic constraint?

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.

What is generic type constraint?

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.)

What keyword allows you to put constraints on a generic type?

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.

Can a generic class have multiple constraints?

Multiple interface constraints can be specified. The constraining interface can also be generic.


2 Answers

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

like image 155
Kyle Baran Avatar answered Sep 27 '22 19:09

Kyle Baran


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.

like image 26
Jamal Salman Avatar answered Sep 27 '22 19:09

Jamal Salman