After coming up against this problem myself in trying to implement a generic Vector2<int/float/double>
in C#, I've done a bunch of investigation into this problem, also described in this question:
Less generic generics? A possible solution for arithmetic in C# generics
These links contain some more background information and fascinating solution approaches:
https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html
http://www.codeproject.com/KB/cs/genericnumerics.aspx
Now that C# 4.0 is out with its new versatile dynamic
type, my question for the brilliant SO community, is this: is it a tool that could be used perhaps to build performant, generic Vector/Matrix/etc. numeric types?
Clearly a Vector2 could be built by simply like so:
public struct Vector2
{
public dynamic X;
public dynamic Y;
public Vector2(dynamic x, dynamic y)
{
this.X = x;
this.Y = y;
}
public static Vector2 operator+(Vector2 a, Vector2 b)
{
return new Vector2(a.X + b.X, a.Y + b.Y);
}
}
but with this approach we have no type constraint here, so you could make a Vector2(3, 12.4572)
. Is there a way that we could mix dynamic members with a type parameter Vector2<int>
to perform our math operations as would be done with int
s?
Perhaps some form of casting could be used to ensure this.X
is a T
, though I don't know how that would perform.