Home > Articles

Introducing C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Flow Control

After this first introduction to C#, we'll examine flow control and control structures. We'll need this information to implement code that is executed only under certain circumstances.

If/Else

Conditional execution is a core component of every programming language. Just like C and C++, C# supports If statements. To see how If statements work, we've implemented a trivial example:

using System;

class  Hello
{
    public static void Main()
    {
        int   number = 22;
        if   (number > 20)
            Console.WriteLine("if branch ...");
        else
        {
            Console.WriteLine("else branch ...");

        }
    }
}

Inside the C# program, we define an integer value. After that the system checks whether the value is higher than 20. If the condition is true, the code inside the If block is executed. Otherwise, the Else branch is called. It's important to mention that the blocks should be marked with parentheses, but this is not a must. Parentheses are normally used to make the code clearer.

When the program is called, one line is displayed:

if branch ...

As we expected, Mono called the If branch.

However, in many real-world scenarios, simple If statements are not enough. It's often useful to combine If statements. When working with Mono and C#, this is no problem:

using System;

class  Hello
{
    public static int Main(String[] args)
    {
        Console.WriteLine("Input: " + args[0]);
        if   (args[0] == "100")
        {
            Console.WriteLine("correct ...");
            return 0;
        }
        else if (args[0] == "0")
        {
            Console.WriteLine("not correct ...");
        }
        else
        {
            Console.WriteLine("error :(");
        }
        return 1;
    }
}

This program is supposed to tell us whether a user has entered a correct number. If 0 is passed to the program, we want a special message to be displayed. Our problem can be solved with the help of else if because it can be used to define a condition inside an If statement. The comparison operator demands some extra treatment. As you can see, we use == to compare two values with each other.

Do not use the = operator for checking whether two values are the same. The = operator is used for assigning values it isn't an operator for comparing values. The C and C++ programmers among you already know about this subject matter.

The way data is passed to the program is important as well. The array called args contains all the values that a user passes to the script. Indexing the array starts with zero. Let's see what happens when we call the program with a wrong number:

[hs@duron mono]$ mono if.exe 23
Input: 23
error :(

In this case, a message is displayed.

Case/Switch Statements

Especially when a lot of values are involved, If statements can soon lead to unclear and hard-to-read code. In this case, working with case/switch statements is a better choice. In the next example, we see how the correct translation of a word can be found:

using System;

class  Hello
{
    public static int Main()
    {
        String inp;
        String res = "unknown";

        // Reading from the keyboard
        Console.Write("Enter a value: ");
        inp = Console.ReadLine();

        Console.WriteLine("Input: " + inp);

        // Read the translation
        switch(inp)
        {
            case "Fernseher":
                res = "TV";
                break;
            case "Honig":
                res = "honey";
                break;
            case "Geschlecht":
            case "Sex":
                res = "sex";
                break;
        }

        Console.WriteLine("Result: " + res);

        return 0;
    }
}

First of all, we read a string. To fetch the values from the keyboard, we use the ReadLine method, which is part of the Console object. After reading the value, we call Console.WriteLine and display the value. Now the switch block is entered. All case statements are processed one after the after until the correct value is found.

One thing has to be taken into consideration: A case block is not exited before the system finds a break statement. This is an extremely important concept. If you use switch, case, and break cleverly, it's possible to implement complex decision trees. A good example is the words Geschlecht and Sex. In German, the words are different, but they have the same English translation. Because we do not use a break in the Geschlecht block, C# jumps directly to the Sex block where the correct word is found. In this block, a break statement is used and so the switch block is exited. Many advanced programmers appreciate this feature.

Let's compile and execute the program:

[hs@duron mono]$ mono case.exe
Enter a value: Fernseher
Input: Fernseher
Result: TV
[hs@duron mono]$ mono case.exe
Enter a value: Geschlecht
Input: Geschlecht
Result: sex

As you can see, the correct result has been found.

Case/Switch statements also provide default statements. Default values help you to define the default behavior of a block if no proper values are found. Using strings in Switch statements isn't possible in most other language—that's a real benefit of C#.

  • + Share This
  • 🔖 Save To Your Account