Strange execution of get accesor in c#?
Posted
by
Kenji Kina
on Stack Overflow
See other posts from Stack Overflow
or by Kenji Kina
Published on 2011-01-09T22:51:57Z
Indexed on
2011/01/09
22:53 UTC
Read the original article
Hit count: 296
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?
© Stack Overflow or respective owner