The standard class function are not able to utilize the standard operators within the c# language, for example the multiple, add, subtraction and divide in a mathematics example.
To overcome this problem, there is a ‘operator’ special syntax that allows for this to take place. The operator can work with any of the c# language standard functions of which you are able to program there functional aspects within the class. The syntax for this is
public static operator ();
for example if there was an return type of int and two integer values passed in the parameter list and using the addition operator.
public static int operator +(int a, int b)
Below is some code that will demonstrate this further within a general code development.
using System;
class operatorBase
{
private int i; // private member of the class
public operatorBase()
{
i = 0;
}
public operatorBase(int init)
{
this.i = init;
}
// get and set the value for the private member i
public int Value
{
get { return i;}
set { i = value;}
}
// the operator +, parameters are the two values that you want to add, can be overloaded with different values
// e.g. (int i2, int i3) for example.
public static operatorBase operator +(operatorBase i2, operatorBase i3)
{
// create the return;
operatorBase locali= new operatorBase();
locali.i = i2.i + i3.i; have access to the internals of passed parameters
return locali; // return the operatorBase class
}
}
class operatorTest
{
public static void Main()
{
operatorBase opBase = new operatorBase();
// set the value to 3 and also output the value;
opBase.Value = 3;
Console.WriteLine(opBase.Value);
operatorBase opBase2 = new operatorBase(4);
// to add to the operatorbases together, but will return an operatorBase, thus bracket the equation and use the .Value to get the value.
Console.WriteLine((opBase + opBase2).Value);
// since creating two new on the fly operatorBase, then the result is an int value again.
Console.WriteLine((new operatorBase().Value = 3) + (new operatorBase().Value = 2));
}
}