Maha

Maha

  • NA
  • 0
  • 321.2k

Increment widget

Feb 18 2014 4:55 PM
In this case w++ and w = w + 1 is not same. Please tell me the reason. Problem is coloured.

using System;

class Widget
{
public int _value;

public static Widget operator +(Widget a, Widget b)
{
// Add two Widgets together.
// ... Add the two int values and return a new Widget.
Widget widget = new Widget();

widget._value = a._value + b._value;

return widget;
}

public static Widget operator ++(Widget w)
{
// Increment this widget.
w._value++;

return w;
}
}

class Program
{
static void Main()
{
// Increment widget twice.
Widget w = new Widget();
w++;
Console.WriteLine(w._value);//1
w++;
Console.WriteLine(w._value);//2

// Create another widget.
Widget g = new Widget();
g++;
Console.WriteLine(g._value);//1

// Add two widgets.
Widget t = w + g;
Console.WriteLine(t._value);//3

Console.Read();
}
}
/*
1
2
1
3
*/


Answers (7)