user34537
user34537

Reputation:

Getter/Setter problem in C#

I am doing

static bool isWorking
    {
        get { return _isWorking; }
        set {
            myform.treeView1.Enabled = !value;
            _isWorking = value;
        }
    }

and stepping through the debugger shows it stops at the first set line. After trying this line instead

set { myform.treeView1.Enabled = !(_isWorking = value); }

I see that isWorking is set but myform.treeView1.Enabled is not. Whats going on?

Upvotes: 2

Views: 1953

Answers (2)

Tom Smykowski
Tom Smykowski

Reputation: 26129

Because (_isWorking = value) returns always true. If you would write:

myform.treeView1.Enabled = !(_isWorking == value);

It works like: if isWorking is equal to value then Disable treeView. But in you case - no

Upvotes: -2

Jon Skeet
Jon Skeet

Reputation: 1503290

What do you mean by "the debugger shows it stops"? Is it possibly that myform is null, or myform.treeView1 is null?

I can't remember the exact evaluation order in this case, but it could explain the symptoms you're describing. Knowing why the debugger "stops" is crucial though. Another possibility is that you're trying to access the UI from a non-UI thread, which would prevent the assignment to Enabled from working properly.

Oh, and please don't use your second version - assignment as a side-effect is very, very rarely a good idea. The only idiomatic use I know is when looping with IO:

string line;
while ( (line = reader.ReadLine()) != null)

and I only consider that acceptable because it's reasonably common. In this case it really looks like you could mean "==" instead of "=".

Upvotes: 9

Related Questions