Ad space (banner)
๐Ÿ”ทVB.NET Lessons
Lesson 15 / 68

Conditional expressions (the If operator)

This lesson covers VB.NET's If operator, with the aim of expressing a branch concisely on one line.

Writing If(condition, value_if_true, value_if_false) treats a branch as a single expression. It corresponds to the ternary operator of other languages and saves writing out a full If statement for a short branch.

The sample code assigns an age-dependent message to message in the single line If(age >= 20, "Adult", "Minor"). Fitting three to five lines of If statement into one is its great advantage.

A common early stumble is overusing it until the code becomes hard to read. When the condition is complicated, or a branch needs to do several things, an ordinary If statement reads better.

In professional work, the If operator is used for straightforward assignments and for picking between two messages. Using it where it fits is what keeps code readable.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run VB.NET directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)