Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator overloading with generics [duplicate]

Possible Duplicate:
Arithmetic operator overloading for a generic class in C#

Here is the code for generic class i have created to add the complex number to overload operator.

public class Complex<T>
{
    public T _a, _b;
    public Complex(T i, T j)
    {
        _a = i;
        _b = j;
    }
    public static Complex<T> operator +(Complex<T> i, Complex<T> j)
    {
        return new Complex<T>(i._a + j._a, i._b + j._b);
    }
}

while working with this i have got an error of,

Error: Operator '+' cannot be applied to operands of type 'T' and 'T'

can any one suggest me the way i can use operator overloading with generics?

like image 600
Sujit Avatar asked Dec 24 '12 11:12

Sujit


1 Answers

The problem is the compiler cannot know if + operator can be applied to T. Unfortunately, there is no way to constraint T to be a numeric type in C#.

However, you might be able to workaround this using the dynamic runtime:

public class Complex<T> where T : struct
{
    public T _a, _b;
    public Complex(T i, T j)
    {
        _a = i;
        _b = j;
    }
    public static Complex<T> operator +(Complex<T> i, Complex<T> j)
    {
        return new Complex<T>(Sum(i._a, j._a), Sum(i._b, j._b));
    }

    private static T Sum(T a, T b)
    {
        return (dynamic)a + (dynamic)b;
    }
}
like image 61
Eren Ersönmez Avatar answered Sep 22 '22 00:09

Eren Ersönmez