tags:

views:

752

answers:

3

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?

+7  A: 

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 "=".

Jon Skeet
Your correct, i am trying to access UI in a non UI thread. I switch the order and _isWorking is properly set. I never notice this until you mention UI in non UI thread -> A first chance exception of type 'System.Threading.ThreadAbortException' occurred in System.Windows.Forms.dll.
acidzombie24
A: 

Because the evaluation of _isWorking = value is always true. You evaluate the action itself, not the value of value.

Edit: Damn was I wrong. Oh well, can't be right all the time! =)

J. Steen
That's not true. The value of the assignment is the assigned value, not always true. If value is false, (_isWorking = value) is also false by definition.
OregonGhost
...and this is why assignment as a side effect of assignment is bad. It caught two people here.
annakata
Oh yes, I never *do* it. Which is probably why I didn't know the actual consequence. =)
J. Steen
A: 

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

tomaszs
No, (_isWorking = value) assigns value to _isWorking and returns value (or _isWorking, which is the same thing now), so if value is false, (_isWorking = value) return false.
Lucas