Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any interfaces shared by value types representing numbers?

Tags:

c#

generics

I would like to be able to create various structures with variable precision. For example:

public struct Point<T> where T : INumber
{
    public T X;
    public T Y;

    public static Point<T> operator +(Point<T> p1, Point<T> p2)
    {
        return new Point<T>
                   {
                       X = p1.X+p2.X,
                       Y = p1.Y+p2.Y
                   };
    }
}

I know Microsoft deals with this by creating two structures - Point (for integers) and PointF (for floating point numbers,) but if you needed a byte-based point, or double-precision, then you'll be required to copy a lot of old code over and just change the value types.

like image 921
dlras2 Avatar asked Nov 05 '22 05:11

dlras2


1 Answers

There's a simple reason why you cannot do that: Operators are non-virtual, i.e., the compiler must know at compile time whether p1.X+p2.X is an integer addition or a double addition.

like image 124
Heinzi Avatar answered Nov 11 '22 03:11

Heinzi