Skip to content

Enum and Delegate generic constraints C# 7.3type safety

Constrain generic type parameters to `System.Enum` or `System.Delegate`.

Prior to C# 7.3 there was no way to constrain a generic type parameter to System.Enum or System.Delegate. This meant generic utility methods for enums or delegates had to rely on runtime checks and lacked compile-time safety.

C# 7.3 allows System.Enum and System.Delegate (and also System.MulticastDelegate) to be used as generic constraints.

Code

C#
public static TEnum Parse<TEnum>(string value) where TEnum : struct, Enum
{
    return Enum.Parse<TEnum>(value);
}

public static Delegate Combine<TDelegate>(TDelegate a, TDelegate b) where TDelegate : Delegate
{
    return Delegate.Combine(a, b);
}
C#
public static object Parse(Type enumType, string value)
{
    if (!enumType.IsEnum)
        throw new ArgumentException("Type must be an enum");
    return Enum.Parse(enumType, value);
}

Notes

  • The Enum constraint is commonly combined with struct to exclude nullable enum types
  • These constraints enable type-safe generic helper methods for enums and delegates without runtime type checks
  • The CLR always supported these constraints — only the C# compiler previously prevented their use

More information