Strange get accessor execution in C #?

I installed a simple program to check how the code is executed inside the get accessor (since I had some problems in another project), and found something rather 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

right!

But instead I got

right!

Lying! WTF!

Just what is going on here?

+4
source share
2 answers

If I were to guess, I would say that the debugger executed 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 them in the IDE :)

Try it on the console; he must behave there.

+10
source

No play.

And don't write getters with side effects.

+8
source

Source: https://habr.com/ru/post/1334859/


All Articles