Bret Walker
Bret Walker

Reputation: 1806

Implement math functions in custom C# type?

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

Answers (6)

Stan R.
Stan R.

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

Ed Schwehm
Ed Schwehm

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

Rytmis
Rytmis

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

Greg Beech
Greg Beech

Reputation: 136657

public static T operator *(T a, T b)
{
   // TODO
}

And so on for the other operators.

Upvotes: 5

Yannick Motton
Yannick Motton

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

CSharpAtl
CSharpAtl

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

Related Questions