Get up to 80 % extra points for free! More info:

Lesson 11 - More on C# conditions

In the previous exercise, Solved tasks for C# .NET lesson 10, we've practiced our knowledge from previous lessons.

In today's lesson, we'll introduce 2 more constructs which are related to the conditions. It's a relaxing tutorial to complete this topic.

The ternary operator

It often happens that we need to set 2 different values somewhere depending on whether a condition applies.

Example - Gender list

For example, imagine we have the gender of the user saved as bool (men would be true) and we'd like to convert it to text. With our current knowledge, we'd write something like this:

bool man = true; // some variable indicating the gender
string genderName;
if (man)
    genderName = "man";
else
    genderName = "woman";
Console.WriteLine(genderName);

The output of the program is of course as follows:

Console application
man

The code is relatively lengthy, even if it only decides between two values. Therefore, programming languages often support the ternary expression.

The ternary expression syntax

Using this operator we can get a value according to the validity of the logical expression. We write it as follows:

(expression) ? value1 : value2

We usually put the condition in parentheses (), followed by a question mark ? and 2 values to be returned. The values are separated by a colon :, the first is returned when the condition is true and the second when it isn't. How simple! :) The name of the operator is derived from the fact that it has 3 parts (condition, first value and second value), therefore ternary.

Example - Use of the ternary expression

Let's try a ternary operator on the example with the gender:

bool man = true; // some variable indicating the gender
string genderName = (man) ? "man" : "woman";
Console.WriteLine(genderName);

Instead of the bool type, we can of course write any other condition in parentheses, eg. (age >= 18) ? "adult" : "underage". In the case of simple expressions, we can omit parentheses.

Nesting ternary operators

Ternary operators can theoretically be nested in each other and thus respond to 3 or more values. However, in most cases of nesting, the code is rather unclear, because it results in long or strangely wrapped lines and it's not possible to see at a glance which part will be executed. Let's show how the nesting of ternary expressions would handle 3 genders:

string gender = "ufo"; // some variable indicating the gender
string genderName = (gender== "man") ? "man" : (gender == "woman") ? "woman" : "unknown";
Console.WriteLine(genderName);

For the example above, it'd be better to create our own method, which we'll show in the following course on the object-oriented programming.

switch with falling-through

We've already seen the switch construct in the "Conditions (branching)". Today we'll show its further use, unlike the ternary operator, it's more of a historical functionality, for which there are not many reasonable uses today. However, it's still part of the standart C# .NET grammar, and you can come across it in some source code.

Example - Trimester

Let's assume that we want to find out which quarter of the year it is by month. Using if and else, the example would look like this:

int month = 2;
if (month >= 1 && month <= 3)
    Console.WriteLine("It's the first quarter.");
else if (mesic >= 4 && mesic <= 6)
    Console.WriteLine("It's the second quarter.");
else if (mesic >= 7 && mesic <= 9)
    Console.WriteLine("It's the third quarter.");
else if (mesic >= 10 && mesic <= 12)
    Console.WriteLine("It's the fourth quarter.");

But how to use switch for such an example? You might come up with the following code:

int month = 11;
switch (month)
{
    case 1:
        Console.WriteLine("It's the first quarter.");
        break;
    case 2:
        Console.WriteLine("It's the first quarter.");
        break;
    case 3:
        Console.WriteLine("It's the first quarter.");
        break;
    case 4:
        Console.WriteLine("It's the second quarter.");
        break;
    case 5:
        Console.WriteLine("It's the second quarter.");
        break;
    case 6:
        Console.WriteLine("It's the second quarter.");
        break;
    case 7:
        Console.WriteLine("It's the third quarter.");
        break;
    case 8:
        Console.WriteLine("It's the third quarter.");
        break;
    case 9:
        Console.WriteLine("It's the third quarter.");
        break;
    case 10:
        Console.WriteLine("It's the fourth quarter.");
        break;
    case 11:
        Console.WriteLine("It's the fourth quarter.");
        break;
    case 12:
        Console.WriteLine("It's the fourth quarter.");
        break;
}

The example works reliably, but the problem is that we didn't help much with this code. We should always avoid such repetitive code.

Falling-through

Let's try it again and use falling-through. If we need to execute the same code in multiple case blocks, we just insert these blocks under each other and don't end each block with break, but the whole group of blocks with one break. Such blocks thus fall through and code common to multiple blocks is executed:

int month = 11;
switch (month)
{
    case 1:
    case 2:
    case 3:
        Console.WriteLine("It's the first quarter.");
        break;
    case 4:
    case 5:
    case 6:
        Console.WriteLine("It's the second quarter.");
        break;
    case 7:
    case 8:
    case 9:
        Console.WriteLine("It's the third quarter.");
        break;
    case 10:
    case 11:
    case 12:
        Console.WriteLine("It's the fourth quarter.");
        break;
}

Sample application output:

Console application
It's the fourth quarter.

This code is already much cleaner. However, the switch construct has added value in case we can't use greater than/less than and it's enumeration of values, here it's more of redundant code full of empty cases.

C# only supports falling-through in empty cases. You can try that once they contain some code, the code will not compile without break. Even from non-empty cases it can theoretically fall-through into others with the goto case value; but this is a bad and confusing practice, so don't use it!

Use falling-through in switch constructs only if you have a good reason for it, but it's important that you can read it when you come across it somewhere.

In the next lesson, More on C# loops , we'll show another loop syntax that we may encounter in foreign source code.


 

Previous article
Solved tasks for C# .NET lesson 10
All articles in this section
C# .NET Basic Constructs
Skip article
(not recommended)
More on C# loops
Article has been written for you by Radek Vymetalik
Avatar
User rating:
4 votes
Activities