Is it possible to define a class in C# such that
class GenericCollection : SomeBaseCollection where T : Delegate
I couldn
Yes it's possible in C# 7.3, Constraints family increased to include Enum
, Delegate
and unmanaged
types.
You can write this code without a problem:
void M<D, E, T>(D d, E e, T* t) where D : Delegate where E : Enum where T : unmanaged
{
}
From Docs:
Beginning with C# 7.3, you can use the unmanaged constraint to specify that the type parameter must be a non-nullable unmanaged type. The unmanaged constraint enables you to write reusable routines to work with types that can be manipulated as blocks of memory
Useful links:
The future of C#, from Microsoft Build 2018
What's new in C# 7.3?
If you are willing to take a compile time dependency on an IL Weaver you can do this with Fody.
Using this addin to Fody https://github.com/Fody/ExtraConstraints
Your code can look like this
public class Sample
{
public void MethodWithDelegateConstraint<[DelegateConstraint] T> ()
{
}
public void MethodWithEnumConstraint<[EnumConstraint] T>()
{
}
}
And be compiled to this
public class Sample
{
public void MethodWithDelegateConstraint<T>() where T: Delegate
{
}
public void MethodWithEnumConstraint<T>() where T: struct, Enum
{
}
}