0

Operator overloading in c#

I'm learning c# .net and I have a small problem I am not understanding why to use "return new " operator in this case static void Main(string[] args) { Counter c1 = new Counter {Value = 45} Counter c2 = new Counter {Value = 55} Counter c3 = c1 + c2; } Class Counter { Public int Value {get; set;} public static Counter operator +{Counter c1, Counter c2} return new Counter {Value = c1.Value + c2.Value} }

11th Mar 2019, 12:19 PM
Best Beats
Best Beats - avatar
2 Answers
+ 1
Because by adding two instances of the counter class, namely c1 and c2, you're creating a new instance of this class c3. Before c3 can get any value it needs to be created first, hence 'return new counter'. Note, youre doing the same thing with c1, c2. First you write new counter (create a counter instance), and then the brackets follow (assign this value to ...).
11th Mar 2019, 12:34 PM
[No Name]
0
Thanks for answe
11th Mar 2019, 12:36 PM
Best Beats
Best Beats - avatar