I've been obsessed with the ternary operator lately, so I wanted to show you guys what it is since beginners don't usually take use of it. The ternary operator (?) allows you to condense an if statement. So lets take this chunk of code for example:
PHP Code:
if (TextBox1.Text == String.Empty)
Button1.Enabled = false;
else
Button1.Enabled = true;
That would disable Button1 if the text box (TextBox1) was empty. Using the ternary operator, you can condense that into 1 single line of code. Here's an example that has the same function as the code above:
PHP Code:
Button1.Enabled = (TextBox1.Text == String.Empty) ? false : true;
The code after the ternary operator (?) sets the Enabled property to false if the statement in the parentheses is true (TextBox1.Text == String.Empty).
":" is a substitute for "else". If the code in the parentheses is false, then it will use the code at the end.
You can use the ternary operator with any data type and even wrap functions around it.
PHP Code:
string MyString = Base64Encode((TextBox1.Text == String.Empty) ? "No Text Entered" : TextBox1.Text);
If needed, it is also possible to embed ternary operators within ternary operators.
PHP Code:
string MyString = (statement) ? ((statement) ? "Yo" : "Hey") : "Hello";
Other Examples:
PHP Code:
Button2.Enabled = Button1.Enabled = (TextBox1.Text == String.Empty) ? false : true;