The "single line if statement" exists in C# and VB.NET as in many other programming and script languages in the following format
lunchLocation = (dayOfTheWeek == "Tuesday") ? "Fuddruckers" : "Food Court";
does anyone know if there is even in VBScript and what's the extact syntax?
An If statement consists of a Boolean expression followed by one or more statements. If the condition is said to be True, the statements under If condition(s) are Executed. If the Condition is said to be False, the statements after the If loop are executed.
Classic ASP uses server-side scripting to dynamically produce web pages that are not affected by the type of browser the website visitor is using. The default scripting language used for writing ASP is VBScript, although you can use other scripting languages like JScript (Microsoft's version of JavaScript).
Conditional statements are used to perform different actions for different decisions. In VBScript we have four conditional statements: If statement - executes a set of code when a condition is true. If...Then... Else statement - select one of two sets of lines to execute.
The conditional ternary operator doesn't exist out of the box, but it's pretty easy to create your own version in VBScript:
Function IIf(bClause, sTrue, sFalse) If CBool(bClause) Then IIf = sTrue Else IIf = sFalse End If End Function
You can then use this, as per your example:
lunchLocation = IIf(dayOfTheWeek = "Tuesday", "Fuddruckers", "Food Court")
The advantage of this over using a single line If
/Then
/Else
is that it can be directly concatenated with other strings. Using If
/Then
/Else
on a single line must be the only statement on that line.
There is no error checking on this, and the function expects a well formed expression that can be evaluated to a boolean passed in as the clause. For a more complicated and comprehensive answer see below. Hopefully this simple response neatly demonstrates the logic behind the answer though.
It's also worth noting that unlike a real ternary operator, both the sTrue
and sFalse
parameters will be evaluated regardless of the value of bClause
. This is fine if you use it with strings as in the question, but be very careful if you pass in functions as the second and third parameters!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With