views:

130

answers:

3

I have two RadioButtons: r1 and r2.

I have to enable both on Enabled = true and disable only unchecked on Enabled = false

public bool Enabled
{
  set
  {
    if(value)
    {
      r1.Enabled = value; // true
      r2.Enabled = value;
    }
    else
    {
      if(!r1.Checked)
      {
        r1.Enabled = value; // false if not checked
      }
      if(!r2.Checked)
      {
        r2.Enabled = value;
      }
    }
  }
}

Which operator have I to use to write each condition in one string?

A: 

I think this is clear enough:

public bool Enabled
{
  set
  {
    if (value || !r1.checked) {
      r1.Enabled = value;
    }
    if (value || !r2.checked) {
      r2.Enabled = value;
    }
  }
}
Roberto Bonvallet
+2  A: 

The following would be similar to what you're doing, but you've got an unhandled case in your original code: if ((!value)&&(r1.Checked)), r1.Enabled is never set (same condition for r2). If you set r1.Enabled and r2.Enabled to true, by default, somewhere, the following code might be sufficient.

r1.Enabled = value || r1.Checked;
r2.Enabled = value || r2.checked;

If you've got weird dependencies, I'm not seeing anything particularly clean...

atk
+2  A: 

The key is that the Enabled property is left as is when value is false and the corresponding check box is checked. So try this:

public bool Enabled
{  
  set
  {  
     r1.Enabled = !r1.Checked? value: value || r1.Enabled;   
     r2.Enabled = !r2.Checked? value: value || r2.Enabled;   
  }
}

or

public bool Enabled
{  
  set 
  {  
      r1.Enabled = r1.Checked? value || r1.Enabled: value;   
      r2.Enabled = r2.Checked? value || r2.Enabled: value;   
  }
}
Charles Bretana
Just want to point out that, while optimized for space, this code isn't really much clearer than the original code. It's definitely better, as it's much clearer that something wonky is going on, but it's not clear as to why. When OP uses this code in his/her project, it'd be worthwhile to add a comment explaining the special condition and why it exists.
atk
I agree. This is not a normal, expected algorithm. Comment for clarity.
Charles Bretana