Why I can not use "+" with an object of type or What type of operators can be used with an object

What types of operators are available for use with an object class?

public static void testing() { object test = 10; object x = "a"; object result = test + x;//compiler error } 

Why can't I use + with an object type?

0
source share
1 answer

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); //Writes: 3 

The same applies to the operator - :

 public static Weight operator -(Weight w1, Weight w2) { return new Weight { Value = w1.Value - w2.Value }; } 

Further reading:

+6
source

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


All Articles