Reputation: 1806
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?
Upvotes: 3
Views: 2909
Reputation: 16065
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 };
}
}
Upvotes: 17
Reputation: 2171
Here is the MSDN article on operators and overriding in C#: http://msdn.microsoft.com/en-us/library/s53ehcz3(loband).aspx
Upvotes: 1
Reputation: 32047
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;
Upvotes: 2
Reputation: 136657
public static T operator *(T a, T b)
{
// TODO
}
And so on for the other operators.
Upvotes: 5
Reputation: 35971
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);
}
}
Upvotes: 3
Reputation: 7512
You need to overload the operators on the type.
// let user add matrices
public static CustomType operator +(CustomType mat1, CustomType mat2)
{
}
Upvotes: 2