Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange execution of get accessor in c#?

Tags:

c#

get

I set up a simple program just to test how the code inside a get accessor executes (since I had been having some issues in another project), and found something quite strange:

class Program {
    static void Main(string[] args) {
        var test = new TestClass();
        var testBool = test.TestBool;
    }
}

public class TestClass {
    private bool _testBool = true;
    public bool TestBool {
        get {
            if (_testBool) {
                Console.WriteLine("true!");
            } else {
                Console.WriteLine("false! WTF!");
            }
            _testBool = false;
            return _testBool;
        }
    }
}

I expected the output to be

true!

But what I got instead was

true!

false! WTF!

Just what is going on here?

like image 569
Kenji Kina Avatar asked Dec 03 '22 03:12

Kenji Kina


2 Answers

If I had to guess, I'd say that the debugger ran it once to show the members of a local variable in the IDE.

If you have side effects in properties (which you shouldn't), don't run it in the IDE :)

Try it at the console; it should behave itself there.

like image 168
Marc Gravell Avatar answered Dec 04 '22 17:12

Marc Gravell


No repro.

And don't write Getters with side effects.

like image 20
Henk Holterman Avatar answered Dec 04 '22 17:12

Henk Holterman