Making a generic type constraint on Func<T>
Asked Answered
D

2

8

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?

Delitescent answered 4/10, 2014 at 22:18 Comment(3)
Probably the proper solution here is to just accept T, then use Func<T> in your class.Renteria
I thought about that, but then I'd have to go like the .NET folks create 17 overloads to support the base Func<T .... T16> case. :) I know it's silly, just wanting to know.Delitescent
Not saying this is a good idea but you could follow this roslyn.codeplex.com/discussions/543871 thread and make a change in Roslyn and compile your code using that compiler.Inhere
G
9

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

Goodnatured answered 4/10, 2014 at 22:24 Comment(0)
M
4

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.

Milord answered 13/9, 2019 at 6:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.