abatishchev
abatishchev

Reputation: 100248

How to optimize boolean operation?

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?

Upvotes: 0

Views: 417

Answers (3)

Roberto Bonvallet
Roberto Bonvallet

Reputation: 33319

I think this is clear enough:

public bool Enabled
{
  set
  {
    if (value || !r1.checked) {
      r1.Enabled = value;
    }
    if (value || !r2.checked) {
      r2.Enabled = value;
    }
  }
}

Upvotes: 0

Charles Bretana
Charles Bretana

Reputation: 146449

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;   
  }
}

Upvotes: 2

atk
atk

Reputation: 9314

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

Upvotes: 2

Related Questions