By default, not every object supports operators such as + , - or others. Imagine the following class:
public class Weight { public int Value {get;set;} }
And the following examples (for example, to calculate the combined weight):
var w1 = new Weight { Value = 1 }; var w2 = new Weight { Value = 2 };
Doing the following will result in a compiler error:
var result = w1 + w2;
The error will look like this:
The + operator cannot be applied to operands of type Weight and Weight
You need to overload the + operator as follows:
public class Weight { public int Value {get;set;} public static Weight operator +(Weight w1, Weight w2) { return new Weight { Value = w1.Value + w2.Value }; } }
Now you can do:
var result = w1 + w2; Console.WriteLine(result.Value);
The same applies to the operator - :
public static Weight operator -(Weight w1, Weight w2) { return new Weight { Value = w1.Value - w2.Value }; }
Further reading:
source share