Add new generic constraints

Topics: C# Language Design
Apr 7, 2014 at 1:04 PM
Edited Apr 7, 2014 at 1:30 PM
When using generics, we are often looking to use some specific constraints that we can't declare today:
  1. A generic must be an enum
  2. A generic must be a decimal, float, double...etc
  3. A generic must support some specific operators (+/-/...etc.)
  4. A generic must be a "blittable" struct (meaning a fixed/pinnable struct that does not contain any managed objects)
  5. A generic must provide a public constructor with some specific parameters (sorry duplicated with Generic condition "where : new()" with parameter] )
There are probably other constraints that could be described. There is also a wide range of programmable static assertions on generics that could be useful... but this is more related to the broader range of code contracts and surely a whole topic in itself!
Apr 7, 2014 at 1:13 PM
I'd also like to see more generic constraints, however, these probably require framework support.

What exactly do you mean by "2. A generic must be a decimal..."? If you know the type, why would you make it a generic type argument?

Constraint (4) should make it possible to use generic pointer types, which would be very much appreciated especially when doing low-level graphics programming.

Concerning (3) and (5), it might be interesting to generalize that similar to what C++ is trying to do with concepts.
Apr 7, 2014 at 1:21 PM
Edited Apr 7, 2014 at 1:23 PM
Expandable wrote:
What exactly do you mean by "2. A generic must be a decimal..."? If you know the type, why would you make it a generic type argument?
Sorry, I was not clear enough for this one. I would expect to be able to constraint a generic to be a float or a double only. Though, I'm not completely sure that if 3. is fully implemented, we would need 2.
Constraint (4) should make it possible to use generic pointer types, which would be very much appreciated especially when doing low-level graphics programming.
Yes, this is exactly what I'm using but only by post patching the IL in order to be able to apply the fixed operator on an array of generic structs! This is indeed pretty standard for low-level graphics/game programming.
Apr 7, 2014 at 11:20 PM
With regard to enum and delegate types, I don't think anything would be necessary beyond removing the code in the compiler that forbids them. Generic code wouldn't be able to do most of the things with enum- or delegate-constrained generics than can be done with enums and delegates, but code would be able to do things like bool HasAnyFlags<T>(this T first, T second) where T:System.Enum and have the compiler validate that both arguments are the same enum type. I've written an extension method which works more than 10x as fast as Enum.HasFlags (using Reflection only once for each type upon which it's invoked), but it annoyingly pops up on many types that aren't enums; being able to restrict its usage to enum types should not be difficult.