Basic Program Structure – Simple and Complex Statements

A quick look to the basic language statements...

Hello, today I will do a quick post on Simple and Complex C# statements. This is VERY BASIC stuff. However, pay attention to it since you don't want to fall in a pitfall during a certification exam. Better keep our basics firm.

Simple Statements

variable declaration statements

string name;
int age;
float height;

assignment statements

name = "alFador";
age = 31;
height = 171.5f;

empty statement

;

I already talked about the empty statement in my article about empty statements here.

method calls

Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(height);

simple statements can be written in multiple lines

Console.
       WriteLine(
                "Statement in multiple lines.");

jump statements : break

for (int i = 0; i < 10; i++)
{
    Console.Write(i + " ");
    if (i == 5)
    {
        Console.WriteLine(" : jumped with 'break' statement. Counter was up to 10.");
        break; // will stop the cycle flow but will continue the method.
    }
}

jump statements : return

for (int i = 0; i < 10; i++)
{
    Console.Write(i + " ");
    if (i == 5)
    {
        Console.WriteLine(" : jumped with 'return' statement. Counter was up to 10.");
        return; // will stop the cycle flow but AND will exit the method.
    }
}

Complex Statements

Complex statements contain simple statements between curly braces . Complex Statements can ...

Control Program Flow

IF Statement

// if, will execute one piece of code if the expression within () is true
int x = 10;
int y = 20;

if (x > y)
{
    Console.WriteLine("Executed if X is greater than Y");
}
else
{
    Console.WriteLine("Executed if X is not greater than Y. In other words Y is greater than X.");
}

Switch Statement

// switch, elegant way of associating code to different cases
string option = "A";
switch (option)
{
    case "X" :
        Console.WriteLine("Will execute if option equals X");
        break;
    case "Y":
    case "Z":
        Console.WriteLine("Will execute for both Y and Z values of option.");
        break;
    case "A":
        Console.WriteLine("Will execute if option equals A");
        break;
    default:
        Console.WriteLine("If any other case was executed, then this will be executed.");
        break;
}

For Statement

// for, will execute the statements within the braces a total number of times
for (int i = 0; i < 3; i++) // 3 times in total
{
    Console.Write(i + " ");
}
Console.WriteLine();

Foreach Statement

// foreach, will iterate throuhg a collection of items
int[] numbers = { 4, 8, 10, 1, 0 }; // this collection could be generated from user input
foreach (int number in numbers)
{
    Console.Write(number + " ");
}
Console.WriteLine();

While statement

// while, will execute it's body while the condition is true
Random rGenerator = new Random();
int rNumber = 0; // get a random int from [0 to 10)

while (rNumber != 8) // the number of times this cycle will execute will change
{                    // everytime you execute this program
    rNumber = rGenerator.Next(10);
    Console.Write(rNumber + " ");
}
Console.WriteLine();

Do-While Statement

// do while, will execute at least 1 time, then it will evaluate
int rNumber2 = 0;
do
{
    rNumber2 = 8; // not actually random but in purpose to proove the cycle will run.
                    // at least once
    Console.Write(rNumber2 + " ");
} while (rNumber2 != 8);
Console.WriteLine();

Indicate Special Cases

Checked statement

// Normally when you 'narrow' values, .NET doesn't throw exceptions
// 'checked' will force .NET to throw exceptios if the 'narrow' operation
// fails. In this case the int bigNumber value fits within the short small variable
// so there won't be any exception. Try to change values and/or remove the checked
// to see by yourself.
checked
{
    int bigNumber = 100;
    short small = (short)bigNumber;
    Console.WriteLine("int bigNumber = " + bigNumber + "     short small = " + small);
}

New Context Statement

// Open a new context
{
    int newVar = 10;
    Console.WriteLine("newVar = " + newVar + "  exists in this context but not outside of it.");
}
// newVar doesn't exist in here!

Using statement

// Help you with IDisposable patterns
// by calling the Dispose() method automatically at the end of the execution.
// In this case, TextWritter has access to 'unmanaged' resources and at the end
// of it's lifetime it needs to close and dispose of them. Using 'using' will
// help us dispose of these 'unmanaged' resources automatically.
using (TextWriter w = File.CreateText("log.txt"))
{
    w.WriteLine("This is line one");
}

Manage Flow Exceptions

Try/Catch/Finally Statements

Console.WriteLine("Try/Catch/Finally Example");
int[] zaNumbers = { 1, 2, 3 };
try
{
    Console.WriteLine("Inside of Try body!");
    for (int i = 0; i < 10; i++)
    {
        Console.Write(zaNumbers[i] + " "); // This for sure will launch an exception!
    }
}
catch (IndexOutOfRangeException e)
{
    Console.WriteLine("Oooopps!!!");
}
finally
{
    Console.WriteLine("Will be executed independently if the exception was thrown or not.");
    Console.WriteLine("Great opportunity to close resources opened in the try { } body.");
}

You can download a copy of these examples in my GitHub solution found here.