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?

halivingston
  • 3,727
  • 4
  • 29
  • 42
  • Probably the proper solution here is to just accept `T`, then use `Func` in your class. – Kendall Frey Oct 04 '14 at 22:30
  • I thought about that, but then I'd have to go like the .NET folks create 17 overloads to support the base Func case. :) I know it's silly, just wanting to know. – halivingston Oct 04 '14 at 22:33
  • 1
    Not saying this is a good idea but you could follow this https://roslyn.codeplex.com/discussions/543871 thread and make a change in Roslyn and compile your code using that compiler. – mjsabby Oct 04 '14 at 22:36

2 Answers2

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

Community
  • 1
  • 1
Kyle Baran
  • 1,793
  • 2
  • 15
  • 30
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.

Jamal Salman
  • 199
  • 1
  • 10