dlras2
dlras2

Reputation: 8486

Are there any interfaces shared by value types representing numbers?

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.

Upvotes: 5

Views: 107

Answers (2)

Heinzi
Heinzi

Reputation: 172280

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.

Upvotes: 2

marcind
marcind

Reputation: 53183

No, there is no such interface.

Upvotes: 0

Related Questions