Search code examples
c#auto-incrementincrement

How to interprete multiple incrementation


I had this question on an interview and I was wondering what would you give as answer if you had the same question. Please don't test the program in the IDE.

public class MyClass
{
    private int _myInt;
    public int MyInt
    {
        get { return _myInt; }
        set { _myInt = value; }
    }

    public MyClass()
    {
        MyInt = 1;
    }
}

What should this program print on the screen ? the more important is Why !

var myClass = new MyClass();

myClass.MyInt += myClass.MyInt;
myClass.MyInt = myClass.MyInt +++ 2;

Console.WriteLine(myClass.MyInt);

Solution

  • lets look at everything

    1. when you do var myClass = new MyClass();, MyInt = 1, as you have initialized it in the constructor

    2. when you do this myClass.MyInt += myClass.MyInt; MyInt was 1, so you added 1 to itself, so now MyInt is 2

    3. when you do this myClass.MyInt = myClass.MyInt +++ 2;; MyInt was 2 and you added 2 to it so it became 4, post ++ implies, increment after assignment (in this case), so it assigns 4 in MyInt

    hence answer should be 4,

    but this was a very simple case and this answer almost states that post ++ means evaluate current expression then increment and pre ++ means increment then evaluate current expression, but it is not exactly so(it appears in your case though), read more about it here, by the language designer himself