0
public struct Vector3<T>
{
    private T X { get; set; }
    private T Y { get; set; }
    private T Z { get; set; }

    public Vector3(T x, T y, T z) : this()
    {
        this.X = x;
        this.Y = y;
        this.Z = z;
    }

    public static Vector3<T> operator +(Vector3<T> v1, Vector3<T> v2)
    {
        return new Vector3<int>(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z);
    }
}

Gives error: Cannot apply operator '+' to oparands of type 'T' and 'T'.

Please help resolve.

  • I'm sure you will find lots of answers if you type the error message in Google. – Selman Genç Apr 03 '15 at 21:28
  • 1
    Look at what you're asking it to do: construct a generic method that can apply + to ANY TYPE. Integers, Strings, GUIDs, System.Net.WebClient, anonymous classes, System.Reflection.AmbiguousMatchException .... ANY CLASS WHATSOEVER. It's not possible. You need to restrict T to some subset interface so that the compiler knows it implements the + operator. – Ross Presser Apr 03 '15 at 21:31
  • There is plenty of good information here http://stackoverflow.com/questions/32664/is-there-a-constraint-that-restricts-my-generic-method-to-numeric-types (also not covering `dynamic` suggestion by Tigran). – Alexei Levenkov Apr 03 '15 at 22:39

1 Answers1

2

You can overcome that limitation on your own risk, by changing templated private members of the class to dynamic type. Example:

public struct Vector3<T>
{
    private dynamic X { get; set; }
    private dynamic Y { get; set; }
    private dynamic Z { get; set; }
    ...
    ....
}

There is no way, unfortunately, in C# to restrict template parameter to numeric values (I guess it is what you are trying to achieve).

Tigran
  • 61,654
  • 8
  • 86
  • 123