dotnet / csharplang

The official repo for the design of the C# programming language
11.53k stars 1.03k forks source link

Proposal: Ability to restrict Generic types #1345

Closed aaronfranke closed 4 years ago

aaronfranke commented 6 years ago

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, or decimal. With only <T> and T x, y, z; I am unable to do things like z = x + y; or if (x > y)

In Java you can do this:

public class ClassName<T extends Number> {

}

Currently the closest equivalent in C# is this:

public class ClassName<T> where T : struct, IComparable, IComparable<T>, IConvertible, IEquatable<T>, IFormattable 
{

}
ufcpp commented 6 years ago

https://github.com/dotnet/csharplang/issues/1233

gafter commented 6 years ago

https://github.com/dotnet/csharplang/issues/110 is specifically intended to support this.

HaloFour commented 6 years ago

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 +.

aaronfranke commented 6 years ago

Oh, good to know. I don't actually use generics in Java, I just want a feature like this in C#.

YairHalberstadt commented 4 years ago

Closing as a duplicate of #110 in general, and #1233 in the specific case of numbers