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开发者_JAVA技巧!
But what I got instead was
true!
false! WTF!
Just what is going on here?
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.
No repro.
And don't write Getters with side effects.
精彩评论