Closed aaronfranke closed 4 years ago
https://github.com/dotnet/csharplang/issues/110 is specifically intended to support this.
To note, Java's support for generic constraints is actually significantly more limited due to Java's inherent limitations with generics. You're not constraining the generic argument to numeric types there, you're constraining the generic argument to a base class of the primitive type wrappers. You're working with Integer
or Float
rather than int
or float
. They are reference types allocated on the heap, nullable, and still unable to be used in arithmetic operations like +
.
Oh, good to know. I don't actually use generics in Java, I just want a feature like this in C#.
Closing as a duplicate of #110 in general, and #1233 in the specific case of numbers
See: https://stackoverflow.com/questions/32664/is-there-a-constraint-that-restricts-my-generic-method-to-numeric-types and https://stackoverflow.com/questions/4732494/cs-equivalent-of-javas-extends-base-in-generics
I would like the ability in C# to restrict the type of a generic to only certain kinds of types, such as numbers, floating numbers, integers, etc. This could allow for the creation of generic math classes. For example, to make a Vector3 that can use
float
,double
, ordecimal
. With only<T>
andT x, y, z;
I am unable to do things likez = x + y;
orif (x > y)
In Java you can do this:
Currently the closest equivalent in C# is this: