John John - 1 year ago 69 Question

How to use a bool as an int?

Say I have two buttons on a form. If the first button gets hidden (visible = false) I would prefer the second button to move over.

In VB I can make a concise assignment:

Button2.Left = 22 - (90 * Button1.Visible)

But this does not work in C#. The only way I could figure out makes the code more wordy than VB (I didn't think that was possible) while making it less readable:

button2.Left = 22 - (90 * Convert.ToInt32(button1.Visible));

That handy shorcut (using a boolean in an assignment to avoid using an if) has existed for decades. Did Micorsoft kill it in C# or is there a way to still use it without adding function calls or the like?

Answer Source

You could create an extension method

public static class Extensions
  public static int ToInt(this bool Value)
    return Value ? 1 : 0;

then use

Button2.Left = 22 - (90 * Button1.Visible.ToInt())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download