Kenji Kina
Kenji Kina

Reputation: 2412

Strange execution of get accessor in c#?

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?

Upvotes: 4

Views: 227

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273274

No repro.

And don't write Getters with side effects.

Upvotes: 8

Marc Gravell
Marc Gravell

Reputation: 1062915

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.

Upvotes: 10

Related Questions