Constraint type inference #6930
-
This is something that has been on many people's wish lists for a while, but now with the addition of generic math it has gained a new use case. Lets say I want to define a generic 3d vector interface: public interface IVector3<T>
{
T X { get; set; }
T Y { get; set; }
T Z { get; set; }
} As well as a public struct Vector3f : IVector3<float>
{
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
} I then want to define a cross product method that works for any vector, as long as the numeric constraints are met: public static class Vector
{
public static TVector Cross<TVector, TElement>(TVector v1, TVector v2)
where TVector : IVector3<TElement>, new()
where TElement :
System.Numerics.ISubtractionOperators<TElement, TElement, TElement>,
System.Numerics.IMultiplyOperators<TElement, TElement, TElement>
{
var result = new TVector();
result.X = v1.Y * v2.Z - v1.Z * v2.Y;
result.Y = v1.Z * v2.X - v1.X * v2.Z;
result.Z = v1.X * v2.Y - v1.Y * v2.X;
return result;
}
} Perfect! Lets try it out: var v1 = new Vector3f();
var v2 = new Vector3f();
var v3 = Vector.Cross(v1, v2); So close:
So instead you have to write the following: var v1 = new Vector3f();
var v2 = new Vector3f();
var v3 = Vector.Cross<Vector3f, float>(v1, v2); Which is not something we want to type all the time. We want C# to infer the types for us. An alternative would be to change the method signature to So I suggest the language team to reconsider constaint type inference. Right now generic math is unable to reach its full potential without it. Vectors and Matrices, Complex numbers and Quaternions, Points, Sizes and Rectangles, these are all multi value math structures that can greatly benefit from this feature. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 13 replies
-
Related/duplicates: #110, #478, #741, #997, dotnet/roslyn#5023 and dotnet/roslyn#15166. And here's a comment describing why it's problematic to do. |
Beta Was this translation helpful? Give feedback.
-
I'm building a library with some complicated constraints. Due to this lack of automatic inference, some of the things I want to do have become undo-able because I can't expect the caller to have to put in my complicated generic arguments. See #8205 |
Beta Was this translation helpful? Give feedback.
-
With the introduction of |
Beta Was this translation helpful? Give feedback.
-
Partial type inference is being considered (#8967), which would allow syntax something like: var v3 = Vector.Cross<_, _>(v1, v2); This avoids the compatibility issue since the |
Beta Was this translation helpful? Give feedback.
Related/duplicates: #110, #478, #741, #997, dotnet/roslyn#5023 and dotnet/roslyn#15166.
And here's a comment describing why it's problematic to do.