Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# get property returns wrong integer

Tags:

c#

Here's the program.

using System;

public class Program {

    public static int Main(string[] args) {

        Stock obj = new Stock();
        obj.Number = 30;
        obj.Number -= 3;
        Console.WriteLine(obj.Number);
        return 0;
    }
}

after executing the program with this code below,

public class Stock {
    int number;

    public int Number {
        get { return ++number; }
        set { number = value; }
    }
}

Screen displays 29. I'm expecting it to be 28.

and with this code below,

public class Stock {
    int number;

    public int Number {
        get { return number * 3; }
        set { number = value; }
    }
}

Gives 261 instead of 81.

Why?

like image 544
Vitas Avatar asked Jun 22 '26 04:06

Vitas


1 Answers

It's called one more time than you are expecting because this line:

 obj.Number -= 3;

is equivalent to obj.Number = obj.Number - 3;

Which is basically calling your getter and setter.

like image 59
MistyK Avatar answered Jun 23 '26 19:06

MistyK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!