Could someone point me to the interface that I need to implement in order to get basic math operators (i.e. +, -, *, /) to function on a custom type?
+2
A:
You need to overload the operators on the type.
// let user add matrices
public static CustomType operator +(CustomType mat1, CustomType mat2)
{
}
CSharpAtl
2009-10-08 14:09:25
+13
A:
You have to use operator overloading.
public struct YourClass
{
public int Value;
public static YourClass operator +(YourClass yc1, YourClass yc2)
{
return new YourClass() { Value = yc1.Value + yc2.Value };
}
}
Stan R.
2009-10-08 14:10:00
In general, if you're doing operator overloading, you're probably dealing with what is a value type not a reference type that needs to (potentially) be a base clas for other types, so you should consider using a struct rather than a class for the underlying Type.
Charles Bretana
2009-10-08 14:22:27
Charles, thanks for that suggestion I have had overlooked it. I edited the code.
Stan R.
2009-10-08 14:26:14
+3
A:
You can find a good example of operator overloading for custom types here.
public struct Complex
{
public int real;
public int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
// Declare which operator to overload (+), the types
// that can be added (two Complex objects), and the
// return type (Complex):
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
}
Yannick M.
2009-10-08 14:10:09
+5
A:
public static T operator *(T a, T b)
{
// TODO
}
And so on for the other operators.
Greg Beech
2009-10-08 14:10:23
+2
A:
What you're looking for is not an interface, but Operator Overloading. Basically, you define a static method like so:
public static MyClass operator+(MyClass first, MyClass second)
{
// This is where you combine first and second into a meaningful value.
}
after which you can add MyClasses together:
MyClass first = new MyClass();
MyClass second = new MyClass();
MyClass result = first + second;
Rytmis
2009-10-08 14:11:13
+1
A:
Here is the MSDN article on operators and overriding in C#: http://msdn.microsoft.com/en-us/library/s53ehcz3%28loband%29.aspx
Ed Schwehm
2009-10-08 14:11:28