Implement math functions in a custom C # type?

Can someone point me to the interface that I need to implement in order to make the basic mathematical operators (i.e. +, -, *, /) function in a user type?

+3
source share
6 answers

You must use operator overload.

public struct YourClass
{
    public int Value;

   public static YourClass operator +(YourClass yc1, YourClass yc2) 
   {
      return new YourClass() { Value = yc1.Value + yc2.Value };
   }

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

And so on for other operators.

+5
source

.

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);
   }
}
+3

.

// let user add matrices
    public static CustomType operator +(CustomType mat1, CustomType mat2)
    {
    }
+2

, , , . , :

public static MyClass operator+(MyClass first, MyClass second)
{
    // This is where you combine first and second into a meaningful value.
}

MyClasses :

MyClass first = new MyClass();
MyClass second = new MyClass();
MyClass result = first + second;
+2

Source: https://habr.com/ru/post/1719621/


All Articles