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?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With