Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: Ability to restrict Generic types #1345

Closed
aaronfranke opened this issue Feb 28, 2018 · 5 comments
Closed

Proposal: Ability to restrict Generic types #1345

aaronfranke opened this issue Feb 28, 2018 · 5 comments

Comments

@aaronfranke
Copy link

aaronfranke commented Feb 28, 2018

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
Copy link

ufcpp commented Feb 28, 2018

#1233

@gafter
Copy link
Member

gafter commented Feb 28, 2018

#110 is specifically intended to support this.

@HaloFour
Copy link
Contributor

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
Copy link
Author

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

@YairHalberstadt
Copy link
Contributor

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants