Thursday, July 23, 2009

C# Basics

Types, Variables and Casting


In C# every variable you declare must have a defined data type, a feature which makes C# a type safe language. This allows the compiler to check your code, before it is compiled, for some errors that will result in a program crash. We will have a look at this in more detail later in this tutorial.

Variables for the basic data types are declared by specifying the data type, followed by the variable name.

int myNumber;
string myString;
decimal accountBalance;

These are three data types that are commonly used in most applications. There is a cheat sheet which shows all the Data Types and Ranges, which lists all the data types, the kind of data they support, the range of values they can hold and their default values.

Naming Variables

Variable names, like method names, have rules that govern how they should be named. Variables and methods must:

  • start with a letter or underscore
  • contain only letters, numbers and the underscore character
  • not use reserved words or keywords

As well as those rules, there are some recommendations as well, for good practice and readability. Some of these are listed below:

Variable names should always be meaningful, but not too verbose. You should not use single letter identifiers except for loop control (where you should use i,j and k) or for mathematical equations (e.g. x = x * y^2).

You should always use the data type most appropriate for its use. For example, a variable to hold day of month would never rise above 31, so a byte would be a better data type over an int or decimal.

Assignment and Initialisation

Variables declared as above will be given default values, as described in the cheat sheet, but you may wish to initialise your variables to something more meaningful or appropriate. You can do this one of two ways.

When you declare the variable:

int myNumber = 12345;
string myString = "Hello World";
decimal accountBalance = 34.87323;

or you can perform a regular variable assignment after the variable has been declared:

int myNumber;
string myString;
decimal accountBalance;

myNumber = 12345;
myString = "Hello World";
decimal accountBalance 34.87323;

Because C# is a type safe language, you will not be able to assign a string to a variable.

int myNumber = "Hello World"; //This will not compile

You can also assign a variable the value of another variable of the same type.

int x = 5;
int y;
y = x;

Variable assignment assigns the value of x to y. X will still retain its original value; Y is just given the value of X.

Types of type

In the .Net world, there are two different types that a data type can be. It can either be a reference type or a value type.

  • Reference types are created on the heap, which is an area of memory where objects are created.
  • Value types are created on the stack, which is a separate area of memory used to hold values.

The Stack and Heap are covered in more detail in the Introduction to .Net tutorials, and reference and value types are covered in depth in the Common Language Specifications topic.

Examples of Value types are int, float, struct, and enum.

Type Casting

Some data types can be assigned to a different type if they can be implicitly cast. This means that a small number can be assigned to a large number, but not vice versa.

Let's take two data types, the byte and the long. As you can see from the cheat sheet, a byte can hold whole numbers between 0 and 255 and a ulong can hold whole numbers between 0 and 9,223,372,036,854,775,807. Think of these as a shot glass and a pint glass.

byte shotGlass;
ulong pintGlass;

In these analogies, please try an imagine that when we "pour" one glass into another glass, the original glass does not loose any of its contents. Rather, an equal amount of fluid is added to the other glass, while the original retains its contents.

Implicit Casting

It makes sense that you can pour the contents of the shot glass into the pint glass; there really is no danger of it overflowing, so the compiler will allow this to happen, without any warnings. This is called an implicit type cast and is done by the compiler automatically each time you assign a variable to another variable.

pintGlass = shotGlass;

Explicit Casting

So what happens if you want to pour the contents of the pint glass into the shot glass? It may be possible, it depends on how much is in the pint glass. The compiler will see this as dangerous as there is a chance that the shot glass will overflow, so it will flag an error and prevent the program from compiling.

shotGlass = pintGlass;

Cannot implicitly convert type 'ulong' to 'byte'. An explicit conversion exists (are you missing a cast?)

It is possible however to say to the compiler, "I know what I am doing, please let me pour the contents of my pint glass into my shot glass." This is called an explicit type cast, and is performed using the data type you are converting to in brackets just before the variable.

shotGlass = (ulong) pintGlass;

In this case the compiler assumes we know what we are doing and allows it.

If the shot glass does overflow, the value of the shotGlass will rollover and start from 0, so if you try and put a value of 256 into the shotGlass, the value would be 0, a value of 257 would be 1, 258 would be 2 and so on.

You should only explicitly type cast when you are certain that the values will fit, and it is sensible to test for this condition before performing the conversion.

Floating Point

Floating-point numbers are able to store values with a decimal fraction as well as a value, for example 2.5632. You can implicitly cast an int to a float or decimal type, but you cannot implicitly cast a decimal or float to an int as an int will not be able to hold the data after the decimal point. You can explicitly cast, however you will loose any decimal data, i.e. 2.5632 cast as an int will become just 2.

Review Questions

Can you spot the invalid variable names in these samples?

  1. int 2counter;
  2. string $myString;
  3. char Initial
  4. class this;
  5. int __hwnd
  1. Invalid. Names cannot begin with a number.
  2. Invalid. Names cannot start with a character other than letters or underscore.
  3. Valid.
  4. Invalid. this is a keyword.
  5. Valid.

Can you guess the result of these explicit casts?

int i = 10;
float pi = 3.14159;
string myString = "Hello World";
decimal price = 9.95;
  1. int y = i;
  2. int y = (int) myString;
  3. int x = (int) pi;
  4. decimal x = (decimal) i;
  1. Implicit cast of int = int. Valid.
  2. Cannot explicitly convert string to int. Invalid.
  3. pi is explicitly converted to int, however loses decimal data. x = 3.
  4. i is explicitly converted to type decimal. Valid

Summary and Conclusion

We have briefly seen a few of the common data types and seen how to implicitly and explicitly cast variables. In the next tutorial we will have a look at the main method and how to create custom methods.

Introducing Methods and Main()


In the last tutorial we wrote a simple hello world program where we saw the Main method, but we didn't explain anything about what it is or what it does. The "Main" is a method that must exist in every program, as the compiler uses this to decide what to do when the program runs. This is called the entry point for the program.

In this tutorial we will look at the Main method and we will also see how to create a new method that we can run (call) from the Main. Let's have a look at our Hello World again.

using System;

class HelloWorld
{
static void Main()
{
Console.WriteLine("Hello World!");
}
}

Listing 1-1, Hello World program

As you can see on line 5, our Main method is declared using

static void Main()

Note: The M is capital and is case sensitive. The Main method must always be marked as static otherwise it cannot be run without creating an instance of the class. We will look at static and void in a later tutorial where we look at types and methods in more detail. In a nutshell they describe to the compiler where the method can be called from (static means can be called without an instance of the class) and what the method will return (void in this case means nothing is returned).

All methods are blocks of code, and a block of code is always encased within curly brackets (braces).

Methods are always executed from the top brace down to the bottom brace, in sequential order. When the compiler reaches the end of the Main method, the program exits.

Creating Methods

We can add another method to our project in much the same way as the Main method. After the closing brace of the Main method, we will add in another method called "myMethod". Also add in an empty code block with open and close braces.

The method name can be anything you like as long as it follows a few general rules:
Method names must:

  1. Be Unique
  2. Not the same as a keyword
  3. Contain only letters or numbers or the underscore character (_)
  4. not start with a number

There are also several guidelines that should be observed for good coding practice, but they do not affect the compiler, or the running of the program.

Going back to our old Hello World program, the code should look like this when you add our new method.

using System;

class HelloWorld
{
static void Main()
{
Console.WriteLine("Hello World!");
}
static void myMethod()
{
}
}

Listing 1-2, Adding a new Method

Now we need our method to do something, so add another line between the braces

Console.WriteLine("myMethod Has Been Called");

Try and build your project now, using Ctrl+Shift+B and hopefully you will receive a successfully built message. Now running the project using the F5 key, or the play symbol on the toolbar.

Can't see the console window?

Depending on the configuration of your installation of Visual Studio, you may see a console window flash up and vanish very quickly. If this is the case we need to stop the program from exiting by adding another line into the Main method. After the Console.WriteLine line, add a new line

Console.ReadLine();

This will cause the program to wait for an input before exiting. Alternatively you can run the program without debugging (Ctrl+F5), which will cause the program to output a message "Press any key to continue…" and wait before exiting. The downside of this method is you cannot debug your program.

Run the program now, and you should see the console window with a line that says "Hello World!".

Hello World Output

Why does it not show "myMethod Has Been Called" as well?

We have not called myMethod yet, so the code in myMethod does not get executed. Press the Enter key to close the program and return to the editor. We can fix our little problem by adding

myMethod()

between the Console.WriteLine and Console.ReadLine lines. This will call myMethod and cause the compiler to break out of Main and into myMethod. When it reaches the end of myMethod, it will return to the point in Main where it left off. This is explained in more detail in a later tutorial about Flow Control.

Now when you run the program, you will see two lines on the console window.

Hello World Output

Completed Source Listing

using System;

class HelloWorld
{
static void Main()
{
Console.WriteLine("Hello World!");
myMethod();
Console.ReadLine();
}

static void myMethod()
{
Console.WriteLine("myMethod Called");
}
}

Listing 1-3, Full Code for Tutorial

Summary and Conclusion

In this tutorial we have seen the Main method and how it works, we covered code blocks using braces and creating a simple method as well as calling it from Main. We also touched on program flow control.

In the next tutorial we will have a closer look at methods, how to pass parameters and returning a result from a method.

Parameters and Return Values

We will see how to pass parameters to a method and how to return a value back, and cover more advanced features like variable length parameters, passing by reference and output parameters.

In our Hello World program we saw the static void Main() method and we created another method the same way using static void myMethod()

What do we do if you want to pass some data to your new function and have it return a value back? How do you capture the result? And how do you pass a parameter? Let's have a look using the code from the last tutorial.

using System;

class HelloWorld
{
static void Main()
{
Console.WriteLine("Hello World!");
myMethod();
Console.ReadLine();
}

static void myMethod()
{
Console.WriteLine("myMethod Called");
}
}

Listing 1-1, Hello World calling a Mathod

Rename the myMethod function to something a bit more meaningful, like addNumbers. You will need to change both lines 8 (calling) and 12 (declaration).

The next thing we need to do is modify our new addNumbers method to accept parameters. We can do this by declaring two variables within the parenthesis. These are method parameters.

static void addNumbers(int x, int y)

Next we need to perform an action on these numbers, so we will add them together and store them in another variable.

int z = x + y;

You can use parameters that have been passed into the method in exactly the same way as you would use a variable that has been declared.

Next we need to change are Console.WriteLine to output the calculated value:

Console.WriteLine("Result of {0} + {1} = {2}", x, y, z);

You can see more about the curly braces and how strings are formatted in the Format Strings cheat sheet.

Your new source should look like this:

using System;

class HelloWorld
{
static void Main()
{
Console.WriteLine("Hello World!");
myMethod();
Console.ReadLine();
}

static void myMethod(int x, int y)
{
int z = x + y;
Console.WriteLine("Result of {0} + {1} = {2}", x, y, z);
}
}

Listing 1-2, passing Values to addNumbers Method

Now, try and Build the project. Your compiler will raise an error:

No overload for method 'addNumbers' takes '0' arguments

This is because we have not passed the correct number of parameters to our function. This is quite a common error, especially when a function takes many parameters.

If you go back up to line 8 where we call our addNumbers method, place the cursor within the brackets and press (Shift+Ctrl+Space) and the Intellisense will tell you the parameters that the method you are calling expects. It will also tell you which parameter you are currently on by highlighting it in bold. Parameters are separated using a comma, so add two numbers in now, and watch how Intellisense updates to help you.

addNumbers(2,2);

Now your project should build and you will see the result of the calculation being displayed.

Returning a Value

Instead of outputting the calculation to the screen, you may wish to return it back to the calling method (the method where the addNumbers method was called from. In this case Main).

We need to make another change to the method. This time we need to change the word void (which means the method does not return a value) into int (which means the method returns a number).

Now we need to remove the Console.WriteLine line and replace it with:

return z;

And that's all we need to do to make our method return a value. We just need to change our calling function to pick up the result.

static void Main()
{
Console.WriteLine("Hello World!");
int result = addNumbers(2,2);
Console.WriteLine("Result of addNumbers = {0}", result);
Console.ReadLine();
}

A Few Notes

The value you use to hold the result of a function must be of the same type as the return type of the method you are calling.
The value you return through return myValue must be of the same type as the methods return type. This is because C# is a type safe language. That means the compiler will make sure that you are not trying to place a string in a variable that is declared as a number.

Other ways of passing data

There are three ways of passing data to and from a method. We have just seen the first way - by value, but there are two other ways.

By Reference

Variables passed in by value are read-only. Within the method you cannot assign a value to a parameter unless it is passed by reference. When you pass a parameter by reference, you pass the memory location rather than the data. The method can then access and modify the memory location.

You can specify that a parameter should be passed by reference using the refkeyword. Parameters passed in this manner are read/write, you can read the value and also write a new value which can be picked up by the calling method.

static void myMethod(ref int myInt)

To call a method with the ref keyword, you also need to specify ref in the parameter list.

int z = 2;
myMethod(ref z);

Output Parameters

The third way is through the use of output parameters and the out keyword. This allows values to be passed out, but not in, thus it is a write-only parameter.

static bool myMethod(out int myInt)
{
Console.WriteLine(myInt); // Will Error;

// Return a value
myInt = 10;
return true;
}

You can see that this method will allow you to return more than one value back to the calling method. You can have as many out parameters as you need.

To call a method with out parameters you need to specify out in the parameter list in the same way as you do with reference.

int a;
if (myMethod(a) == true)
{
Console.WriteLine(a);
}

Difference between reference and output parameters

One of the main differences between the two is that parameters passed by ref do not have to be assigned to, whereas output parameters must be assigned to before the method exits.

Variable Length Parameters

Sometimes it is required to pass n number of parameters to a method. A good example is a method to calculate the average of a series. You could pass in 1, 2, 3 or 10 values. Variable length parameter lists can be used instead of multiple int declarations. They are declared using the params keyword. Variable length parameters are always passed by value.

static float average(params int[] items)
{
int total = 0;
foreach (int value in items)
total += value;
return (total / items.Length);
}

Console.WriteLine(average(1,2,3));
Console.WriteLine(average(1,2,3,4,5,6,7,8,9));

This technique can be used to pick up on arguments passed into the program in the Main method:

static void Main(string[] args)

Summary and Conclusions

We have seen how to pass numbers to a method and perform a calculation on them, returning the value back to method it was called from. We used variables of type int in this example, but you can use any of the defined types, a class, array, struct or any other data type.

C# Operator List


C# has a large number of operators, some will be used in every single program or module, while others you may not ever use.

The most common of the operators are the arithmetic and logic operators. These will be very familiar to you is you know other programming languages, or mathematics.

Arithmetic

Operator Action Example Result
+ Addition z = 1 + 2 z = 3
- Subtraction z = 1 - 2 z = -1
* Multiplication z = 2 * 2 z = 4
/ Division z = 22 / 7 z = 3.142857
% Modulus z = 22 % 7 z = 1
The modulus operator (%) computes the remainder after dividing its first operand by its second.

Logic

Operator Action Example Result
&& Logical AND true && false
true && true
false && false
false
true
false
|| Logical OR true || false
true || true
false || false
true
true
false
! Logical NOT true && !false true

Increment and Decrement

Operator Action Example Result
++ Increment a=1;
a++;
a = 2
Decrement a=1;
a–;
a = 0;

Relational

Operator Action Example Result
== Equals x = 1;
x == 1
true
!= NOT Equals x = 1;
x != 1
false
< Less than x = 1;
x <>
true
> Greater than x = 1;
x > 0;
true
<= Less than or equal to x = 1;
x <= 0
false
>= Greater than or equal to x = 1;
x >= 5
false

Assignment

Operator Action Example Result
= Assignment x = 1
+= Incremental Addition a=1;
a += 3;
a = 4;
-= Incremental Decrement a=1;
a -= 3;
a = -2;
*= Multiply by a=2;
a *= 4;
a = 8;
/= Divide by a=8;
a *= 2;
a = 4;
%= Modulus or Remainder a=8;
a %= 3;
a = 2;
&= Logical AND "x &= y" is equivalent to "x = x & y"
|= Logical OR "x |= y" is equivalent to "x = x | y"
<<= Left Shift "x <<= y" is equivalent to "x = x <<>
>>= Right Shift "x >>= y" is equivalent to "x = x >> y"

others


Operator Action Example Result
& Logical AND if (false & ++i == 1) false
| Logical OR true | false
false | false
false
true
^ Logical Exclusive XOR false ^ false
false ^ true
true ^ true
false
true
false
~ Bitwise Complement x = ~0×00000000 x = 0xffffffff
<< Left Shift 1 <<> 2
>> Right Shift -1000 >> 3 -125
?? Default Value int y = x ?? -1; if x = null y = -1 else y = x
:? Conditional Operator condition ? expression if true : expression if false

Conditional Statements


Having just seen the C# Operators in the last tutorial, we will now look at using the logical operators in more depth and look at the conditional statements.

Conditional statements allow different sections of code, or actions, to be executed depending on a condition being met. Conditions can be used to validate user input, display certain data depending on date or day of week, or any one of thousands of conditions.

If… Else

The most commonly used conditional statement is the If… Else block, in which a statement is evaluated to true or false and depending on the result, a different section of code is executed.

In this sample the statement checks if the condition is true, if it is it executes the first block of code. If the condition is false then it executes the second.

Conditions in the if statement must ALWAYS evaluate to TRUE or FALSE.

int x = 5;

if (x >= 3)
{
Console.WriteLine("X is greater than or equal to 3.");
}
else
{
Console.WriteLine("X is less than 3.");
}

Listing 1-1, Sample If… Else statement

Have a play by changing the value of X and seeing which code block is executed.

If you only have ONE statement to be executed, like our example, you can omit the braces, but if you have more than one statement you will need the braces. This can make the code a little easier to read, but some consider it bad form.

int x = 5;

if (x >= 3)
Console.WriteLine("X is greater than or equal to 3.");
else
Console.WriteLine("X is less than 3.");

Listing 1-2, Condensed If… Else statement

You don't need to have an else statement. If all you want is to output something on Monday for example:

if (dayOfWeek = Monday)
Console.WriteLine("Today is Monday");

Listing 1-3, If statement

This will write out Today is Monday only if dayOfWeek is Monday, otherwise the code is skipped over.

Nested If Statements

If you have multiple scenarios, you can nest if… else statements:

if (dayOfWeek = Monday)
Console.WriteLine("Today is Monday");
else if (dayOfWeek = Tuesday)
Console.WriteLine("Today is Tuesday");
else if (dayOfWeek = Wednesday)
Console.WriteLine("Today is Wednesday");
else if (dayOfWeek = Thursday)
Console.WriteLine("Today is Thursday");
else if (dayOfWeek = Friday)
Console.WriteLine("Today is Friday");

Listing 1-4, Nested If… Else statement

But this can get a little complicated for many conditions so a much easier and efficient method would be to use a switch statement.

Switch Statement

In the previous example with the multiple daysOfWeek, by the time Friday is tested the program has executed four if statements which is a very inefficient method. The code is also a little difficult to read and understand, so a much better method would be to use a switch case statement.

The above example can be simplified to this:

switch(dayOfWeek)
{
case "Monday":
Console.WriteLine("Today is Monday");
break;
case "Tuesday":
Console.WriteLine("Today is Tuesday");
break;
case "Wednesday":
Console.WriteLine("Today is Wednesday");
break;
case "Thursday":
Console.WriteLine("Today is Thursday");
break;
case "Friday":
Console.WriteLine("Today is Friday");
break;
}

Listing 1-5, Switch statement

As you can see, this is much easier to read, and there is only one conditional statement that gets executed so the code is more efficient and faster to execute. Each section of code to execute ends with a break keyword. This tells the compiler that the case has ended. Unlike some languages, such as PHP, you cannot `fall through` case blocks if code exists. You can only fall through when one case directly follows another case statement:

case "Saturday":
Console.WriteLine("Today is a Weekend"); // This will ERROR!
case "Sunday":
Console.WriteLine("Today is a Weekend");
break;

Listing 1-6, Sample fall through case - Invalid

case "Saturday":
case "Sunday":
Console.WriteLine("Today is a Weekend"); // This is OK!
break;

Listing 1-7, Sample fall through case - Valid

Another useful part of the Switch…Case block is that of a default action. If none of the cases specified are met, then the default will be executed.

switch(dayOfWeek)
{
case "Monday":
Console.WriteLine("Today is Monday");
break;
case "Tuesday":
Console.WriteLine("Today is Tuesday");
break;
case "Wednesday":
Console.WriteLine("Today is Wednesday");
break;
case "Thursday":
Console.WriteLine("Today is Thursday");
break;
case "Friday":
Console.WriteLine("Today is Friday");
break;
default:
Console.WriteLine("Today is a Weekend!!!");
break;
}

Listing 1-7, Switch statement with default

Default must always be the last statement.

C# allows the use of other keywords as well as break to control the flow of the Switch statement. You can use goto, return and throw.

Goto

The use of Goto does not fall within the structured programming methodology and should be avoided at all costs.

Return

Used to return a value back to the calling function.

Throw

Throw is used to raise an exception, which will be captured by your Try… Catch block. This will be covered in much more detail in the section about Exception Handling.

Summary and Conclusions

We have seen how to use conditional statements to perform different actions based on whether the condition evaluates to true or false. We also saw how a switch statement can be used where there are multiple if else statements to improve readability and performance.

In the next tutorial we will look at how to iterate, or loop, in order to repeat a task many times.

Looping and Iteration


It is often necessary to repeat a task many times. This is a process known as iteration, or looping. C# has a number of methods for looping: Do, While, For and Foreach.

The type of iterative loop is governed by how it should perform and what data types are involved. Some loops check the exit condition before they exit the loop, while others guarantees at least one pass.

The While Loop

The simplest loop is the while loop. This is a loop that executes a code block while the condition is true.

int i;
while (i<10)
{
Console.WriteLine("Loop {0}",i);
i++;
}

Listing 1-1, A simple while loop

There is a danger however that you will get caught in an infinite loop. This is a loop where the exit condition is never met. An example of an infinite loop would be if you forgot the i++; line. i will always be less than 10, so the loop will never exit.

A while loop will check the condition before entering the loop, and if the condition is met first time there will be no loop.

The Do… While Loop

The do while loop is similar to the while loop, except that it does not check the condition until the end of the first iteration. You are guaranteed to have a minimum of one iteration every time.

int i;
do
{
Console.WriteLine("Loop {0}",i);
i++;
}while (i<10);

Listing 1-2, A simple do… while loop

Again, you must increment the loop counter yourself to avoid being caught in an infinite loop.

The For Loop

The for loop is one of the most common type of loop. It will loop from a starting count to a ending count then stop. For example you can loop through numbers 1 to 10. The basic format for a for statement is:

for (start value; end condition; increment counter)
{
// Code to repeat
}

Listing 1-3, A simple for loop

Looping from 1 to 10 as our first example will be coded as follows:

for (int i=1; i<=10; i++)
{
// Code to repeat
}

Listing 1-4, A simple for loop

It looks a bit complicated, so we'll go through each aspect in turn.

int i=1: Declares a variable called i and initiates the value to 1. This is the loop starting value.

i<=10: The program will loop as long as i <= 10. Once this condition is no longer met (i.e. i > 10) the loop will exit.

i++: Increment the value of i by 1 for the next iteration.

You cannot change the value of i within the code to repeat, but you can access its value:

for (int i=1; i<=10; i++)
{
i = 67; // This line will ERROR!
Console.WriteLine("Loop: {0}", i);
}

Listing 1-4, Using for counters

Once the erroring line is removed, the program will output:

Loop: 1
Loop: 2
Loop: 3
Loop: 4
Loop: 5
Loop: 6
Loop: 7
Loop: 8
Loop: 9
Loop: 10

The ending condition does not have to be a fixed value, you can use a function that returns an int. For example, you can loop through all the values in an array (these will be in detail covered later) using the count function to return the number of elements in the array. You can then use the value of i to access the array element.

string[] daysOfWeek = new string[] {
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday"
};

for (int i=0; i<=daysOfWeek.Length; i++)
{
Console.WriteLine("Day of Week: {0}", daysOfWeek[i]);
}

Listing 1-5, Using for loop on arrays

Will output:

Day of Week: Monday
Day of Week: Tuesday
Day of Week: Wednesday
Day of Week: Thursday
Day of Week: Friday

Foreach

The for statement has many individual statements that implement the loop mechanism to iterate through the items of an array. It isn't particularly intuitive and it is prone to error. A foreach statement is a better method for looping through elements of an array.

To iterate through the daysOfWeek array from the previous code, the for loop can be replaced with a foreach:

foreach(string Day in daysOfWeek)
{
Console.WriteLine("Day: {0}", Day);
}

Listing 1-6, Foreach loop

It is much easier to understand what is happening in this example. We declare a value Day of type string (must be the same as the array data type) and it automatically gets assigned the value of daysOfWeek. On the next iteration we get the next array item, and so on until the end of the array is reached.

You cannot assign to the value of Day in this example as it is read only.

Summary and Conclusions

We have seen the four iterative loops, while, do while, for and foreach, and we have seen how they can be used to repeat an action many times on certain types of data.

In the next tutorial we will look at how the compiler flows through the code from start to finish. We will also have a look at flow control.

Flow Control and Entry Points


In C# applications, code is executed in a specific sequence. Execution of code starts at the program entry point, usually the Main method. From there it executes code sequentially until it gets to the end of the entry point, then the application closes.

The various code blocks affect the flow of execution; you can jump out to a method or skip over sections. The easiest way to see how a program flows is by using the . We won't be doing any debugging, but we will use the step into tool to have a look at how the compiler executes the code.

Start a new console project and copy in the following code:

class Program
{
static void Main()
{
Console.WriteLine("This is the first instruction executed.");

for (int i = 0; i < 5; i++)
{
Console.WriteLine("In a loop…");
//We will do this five times
}

int result = myMethod();

if (result == 1)
Console.WriteLine("myMethod returned 1");
else if (result == 2)
Console.WriteLine("myMethod returned 2");
else if (result == 3)
Console.WriteLine("myMethod returned 3");
else
Console.WriteLine("myMethod returned something else");

switch (result)
{
case 1: Console.WriteLine("myMethod returned 1"); break;
case 2: Console.WriteLine("myMethod returned 2"); break;
case 3: Console.WriteLine("myMethod returned 3"); break;
default: Console.WriteLine("myMethod returned something else"); break;
}
}

public static int myMethod()
{
return 3;
}
}

Once the code is in the editor, press F11 to start the debug step into tool. The console window will flash up, and then return to the editor. You will see that the first brace of the Main() method is highlighted in yellow. Press F11 again and it will jump down to the Console.WriteLine line. This is the line that is just about to be executed. Keep pressing F11 and you will see how the program executes the code. When it gets to the for loop, notice how it checks the conditions in the brackets. First it initialises the variable and then checks the exit condition before going into the loop for the first time. Press the F11 key a few more times and you will see that the value of i gets incremented, then it checks the exit condition again.

After a couple more iterations, the flow will jump down to the line that calls myMethod and then we see the flow jump again to the first brace of the myMethod statement, which returns 2. We then jump back up to the myMethod calling line and carry on from where we left off.

Next we have some nested if statements. In the previous tutorial about conditional statements we said that the nested if statement were inefficient. Now we will see the visual proof and compare that to the switch… case statement.

Step through the if statements with the F11 key and see how each one is executed in turn until we find one that is true. Keep on pressing the F11 key and compare the if statements with the switch statement. Notice how only one statement gets looked at and how many times less you press the F11 key.

After the switch statement the flow falls down to the last brace of the main function and then the program will end.

Entry Points

Every .Net assembly must have an entry point called Main(). This is the method that will be called when the assembly is loaded and is the controlling routine. When the entry point method has finished executing, the program will exit.

An assembly can have more than one Main() method, but only one Main can exist in a single class.

namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main Called");
}
}

class Program2
{
static void Main()
{
Console.WriteLine("Main2 Called");
}
}
}

To specify which Main should run you need to use the /main compiler option, either on csc.exe or within the IDE. To configure the IDE to compile multiple entry points you need to:

  1. Select the project in Solution Explorer and bring up its properties.
  2. Click on the Application tab.
  3. Make sure that the Enable application framework check box is disabled.
  4. Change the value in the start-up object box to include /main:Program2 where program2 is the class containing the entry point to be used.

Unless you specify which entry point to use, the code will not compile.

Summary and Conclusions

In this tutorial we saw how flow of execution jumps around the code, but follows a set pattern. We also saw that the switch statement is more efficient than multiple nested if statements.

Stepping into code using F11 is one of the most important features of the C# debugger and allows the programmer to analyse each line before it is executed. This is very useful for finding the cause of errors.

Your First Console Application

In this short tutorial, we will create a simple C# Console Application to verify that our Visual Studio is installed correctly and that the .Net Framework is working properly. We will create the famous "Hello World" application.

Having just installed Visual Studio, we should just test that the installation is working ok. To do this we will create a "Hello World" console application. We will introduce a few constructs that may be unfamiliar, but don't worry, we will cover these in greater detail in the upcoming tutorials.

For now, open up the Visual C# and create a new Console Application. In order to keep things as simple as possible for the first lesson, select all the code (Ctrl+A) or Edit » Select All, and delete it. Next, you need to type in, or copy and paste the following code into the editor.

using System;

class HelloWorld
{
static void Main()
{
Console.WriteLine("Hello World!");
}
}

Listing 1-1, Hello World Application

You should now run the program by pressing (Ctrl+F5) which will start without debugging, or from the menu select Debug » Build Without Debugging. I'll explain why in the next tutorial, but now you should see the console window that says "Hello World!"

Let's Examine the Code

On the first line, we are telling the compiler that we want to use something called System. System is a namespace that is provided by Microsoft. Namespaces are an important concept in C# (and the .Net Framework in general) and will be covered in a future tutorial. It is similar to include statements in languages such as C/C++ and PHP.

The next line of code is creating a class called HelloWorld. Again, a class is a fundamental concept in object orientated programming and will be covered in great detail in future tutorials. For now, think of a class as a container. Everything must be contained within a class in C#, unlike C/C++ and PHP where you can have variables inside or outside a class or function.

The next line of code defines the Main function for the program. We don't need to worry too much about Main at this stage, as we will cover it in a later session. Finally, our last line of code simply tells the program to write a line onto the screen. Console.WriteLine will write a line of text to the console screen and automatically add a new line, carriage return to the end. Notice there is a semi-colon at the end of the line. C#, like a lot of programming languages, uses the semi-colon to separate lines of code or operations. Every statement will have a semi-colon at the end.

Summary and Conclusion

Now you have built your first C# program using Visual C# Express, and we have introduced the basics of C# programming as well as some important concepts. In the next tutorial we will look at the features of the Visual Studio IDE and see how it can make our lives easier, and save a lot of typing.

Visual Studio Task List


Visual Studio contains a nice feature that is a Task List. This view is similar to the Output view, but shows all the tasks associated with the project or solution.

To view the task list select View menu then Task list (Ctrl+W, T). Tasks can be added with the "Create User Task" button and checked off when done.

Visual Studio Task List

The best feature for me however is its ability to automatically add and track TODO comments in your source code. When coding I often add a comment for things that need fixing or implementing in the future, the task list will pick up on these items so you can view them all and go directly to them.

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
myArrayList myList = new myArrayList();
// TODO: Genereate these dynamically
myList.Add("iulwrg");
myList.Add("3847987");

Console.WriteLine(myList.ToString());
}
}

class myArrayList : System.Collections.ArrayList
{
public override string ToString()
{
//HACK: This is a messy way, but works for now. Make it better.
string result = "";

//UNDONE: Removed for testing
//string[] theItems = (string[])base.ToArray(typeof(string));

foreach (string item in theItems)
{
result += " " + item;
}
return result;
}
}
}

This code will be scanned by the task list view and will pickup on the comment tags TODO, HACK and UNDONE.

You can define your own tags from the options screen (Tools » Options » Environment » Task List »Task List Options and add a comment token with the appropriate priority). FIXME is my personal favorite.

Visual Studio Task List - Comment Tags

.Net Command Line Tools


Visual Studio provides a set of command line tools to software engineers to acomplish some tasks that are either not available in the IDE or tools that can be run in batch.

Some of these tools are essential for distributing applications over the Internet. Listed below are the main tools and essential tools, together with a description and example usage. This is not a comprehensive or definitive list of the tools.

Csc.exe - C Sharp Compiler

Command line compiler tool compiles .cs files to .exe.

csc.exe mySource.cs - compile to mySource.exe with a target of release.

csc.exe mySource.cs /debug - compile to mySource.exe with a target of debug.

csc.exe mySource.cs /out:Demo.exe - compile to Demo.exe.

csc.exe mySource.cs /target:library - compile to mySource.dll.

csc.exe *.cs - compiles all cs files to exe.

csc.exe -? - display full list of command line parameters.

Gacutil.exe - Global Assembly Cache Tool

Command line tool to inspect the current machine's global assembly cache. You can view, install or uninstall assemblies from the GAC with this tool.

gacutil.exe /l - List all assemblies currently installed on the machine.

gacutil.exe /i myfile.dll - Install an assembly into the GAC.

gacutil.exe /u myfile.dll - Uninstall an assembly from the GAC.

gacutil.exe - display full list of command line parameters.

Ildasm.exe - Intermediate Language Dissembler

Not strictly a command line tool, but not installed onto the start menu. This program will provide a disassembly of a file provided that it is a Portable Executable (PE) executable (generated by the ILASM tool or C# compiler).

The tool will inform you of any references the program has, the classes, methods and data objects in the executable and other debug information.

Ilasm Intermediate Language Assembler

Compile Intermediate Language to Portable Executable (PE)

ilasm.exe source.il - compiles to source.exe.

ilasm.exe source.il /dll - compiles to source.dll.

ilasm.exe source.il /key:keyfilename - compiles to source.exe using keyfilename to strongly signed private key.

Sn.exe Strong Name Tool

Helps sign assemblies with strong names. It provides options for key management, signature generation and signature verification.

sn -k mykey.snk - generate a random key and store it in mykey.snk.

sn -v mykey.snk - verify an assembly

XML Documentation


Visual Studio 2003 and onwards provides the ability to generate project documentation using comments in the code with embedded xml tags. These can be easily converted to a printable or human readable document using stylesheets.

The code editor will automatically provide the XML tags, all you need to do is to fill in the text as you code. XML documentation is slightly different from normal code comments in that it uses three forward slashes (///) instead of the two. The editor will provide a list of tags that you can use, including a title and description for methods.

By typing /// in front of a method, the editor will auto complete a basic documentation layout for that method.

///
///
///

///
static void Main(string[] args)
{

All you need to do is fill in a summary of the method (what it does, called by, any data it returns etc…) and a description of the parameters it takes.

Using IntilliSense (Ctrl+Space) you can bring up a list of tags that can be used, including examples, seealso and permissions.

It is good practice to comment your code as you progress.

A well-commented application permits a developer to fully understand the structure of the application and how the various aspects interact with each other. It also allows other developers to understand the project much quicker as they spend less time trying to work out what everything does.

When your code is complete and commented you can generate documentation by configuring the project properties.

Either right click the project in the Solution Explorer or select Properties from within the Project menu. At the bottom of the build tab there is an option to generate XML Documentation. Just enter a path for the documentation to be stored within. It will default to your project directory + "bin/debug/ .xml".

You can also use the command line tool, csc.exe, to generate a documentation file:

csc program.cs /doc:my-xml-documentation.xml

This will generate an XML file containing the documentation which you can use XML Transformation on to generate a "pretty printed" version.

The text within the

tags is used by IntelliSense as the method description when prompting for info in the code designer. If you are developing code that will be reused by different people it is highly recommended that each method have at a minimum a summary section.

Getting Started with Visual Studio

In this tutorial we cover downloading and installing Microsoft Visual C# Express and Visual Web Developer, obtaining a registration key and a quick walkthrough of the development environment.

If you already have Visual C# or Visual Studio installed on your machine, you can skip this tutorial and go straight to creating your first console application.

The first thing you will need is a copy of Microsoft Visual Studio. We will be using Visual Studio 2005 Professional for most of the tutorials on this site. If you do not have access to Visual Studio, you can download Visual C# Express for Free from Microsoft. There is no difference in the programming language between Visual Studio and Express Editions, however the Express versions will not allow you to write all of the project types, and there are a lot of features removed from the Express version in order to streamline the environment for beginners.

Visual C# ExpressIf you do not have a copy of Visual Studio 2005 Professional, you can download the Express version for Free from the Microsoft site: Visual Studio Express.

Once you have loaded up the Microsoft website, you will need to click on the Download link which will then give you a step by step download guide. You will need to download the Visual Web Developer for developing ASP.Net web pages and Visual C# Express for developing Windows Forms Applications.

Installation

Once you have downloaded the set-up file (around 3MB) for the required product, you can launch the installer, which will download and install the full Express Studio (35MB). During the set-up process you will be asked if you would like to download optional components, either Microsoft SQL Server 2005 Express Edition or MSDN 2005 Express, which contains a lot of documentation (also available on the Microsoft website). Both of these options can be installed at a later date if you just want the basic Visual Studio installed right now.

When the file is downloaded you should run it and the installer will download the rest of the files and install them into the directory of your choice. It does take a little while to download and install depending on the speed of your Internet connection and computer speed.

Visual C# Express

Once installed, you can launch Visual C# Express from the Start Menu, and when it is done loading you will be presented with the Start Page, where you can see the latest C# news from Microsoft, as well as your recent projects and some shortcuts to common tasks.

Visual C# Express will allow you to create the following project types:

  • Windows Application
  • Class Library
  • Console Application
  • Empty Project
  • Screen Saver
  • Movie Collection Sample App

For the introduction tutorials we will be using only the Console Application project type.

Visual Web Developer

If you would like to be able to develop websites using ASP.Net, you will also need to download and install Microsoft Visual Web Developer, which can be obtained from the same address as Visual C#. Download and install instructions are exactly the same for both products.

Visual Web Developer will allow you to create the following project types:

  • ASP.Net Website
  • ASP.Net Web Service
  • Personal Website
  • Empty Website

When creating a new project, don't forget to change the language to C#.

Registration

Register Visual C#You must register any of the Visual Studio Express products within 30 days of installation to continue using them. Registration is free, then Microsoft will send you an activation code you can use to activate your Express package.

When you click on the bubble you will be presented with a dialog asking for a registration key. If you do not have a registration key you can click on "Register Now" where you will be directed to the Microsoft site. You will need a Microsoft Passport Live ID to sign in, and there is a short questionnaire to fill in, and then Microsoft will send you a 14 digit registration key which you can copy and paste into the registration dialog of Visual C#.

Summary and Conclusions

Now we have a copy of Visual C# Express installed we will have a look at creating our first console application - "Hello World" and introduce a few new concepts of C#.

Using the Integrated Development Interface

In this tutorial we will look at the Visual Studio Integrated Development Interface (IDE) and see how it makes our software development much easier. We will look at syntax highlighting, Intellisense and the toolbars. We will also look at different methods of running an application.

For this tutorial we will be using the free version of Microsoft Visual C# Express to demonstrate the features of the development interface, although there is not a great difference between Visual C# Express and the full Visual Studio.

Syntax Highlighting

You have probably noticed that as you type code in, Visual Studio will change the colour of the words. This is Syntax Highlighting and it the there purely to aid readability.

In general:

  • keywords are blue
  • comments are green
  • strings are red/brown
  • classes are gray

You can change these colours from within the program settings dialog box if you would prefer different colours.

IntelliSense

Using our hello world application from the last tutorial, we are going to invoke Intellisense and let it write code for us. If you types in the code in the last tutorial you will have seen Intellisense, however if you used copy and paste to insert the code, then now you will see Intellisense.

IntellisenseStart off my deleting the Console.WriteLine line, then just type 'C'. Notice a popup window with a list of items beginning with 'C', also note that Console is the highlighted item. This is the item that Visual Studio thinks you are most likely to use in the current context. We can now press Enter, or just '.' and Intellisense will type the rest of the word for you, and bring up another selection box, this time with WriteLine selected.

You can use the arrow keys to select different items on the list. Scroll up to C and notice that Console is not on the list any more. This is because Intellisense will only offer suggestions based on the current context. For this little example it will show all the methods and properties of the Console.

As we are looking at 'C' on the list, type in 'W' and the Intellisense will jump back down to WriteLine. We can see by the icon (see below for examples) that WriteLine is a method we can call, so now type in an open parenthesis and Intellisense will now give you the method name, a description of what it does and the parameters that it takes. Notice in the top left it says "1 of 19″, this function has been overloaded and can take many different types of parameters. Don't worry about this just yet though, but you can use the up and down keys to look through them if you wish.

What is the minimum number of keystrokes needed to type Console.WriteLine("Hello World!");?
19: C.("Hello World!");

If for some reason Intellisense does not automatically popup, you can use (Ctrl+Space) to have it popup at the cursor.

Intellisense Icons

Here are a few of the common icons used in Intellisense and what they mean. Don't worry if you don't understand the terms, they are all explained in later tutorials.

Regions and Blocks

Visual Studio and Visual C# allow sections of code to be hidden away, or collapsed. A section of code between two braces is called a region, and can be collapsed or expanded by using the plus or minus icon near the gutter. The gutter is the grey column down the left hand side of the code window. We will see what the gutter is used for when we look at Debugging.

You can collapse block level code that is nested within your methods, you can collapse the namespace, or you can collapse any block of code between the two.

The code does not get deleted, just hidden from view. This is very useful because it can hide away code that you may not be interested in and declutter the code window, so all your attention is on the code you are writing.

You can also define your own collapsible blocks of code by using the region and endregion keywords. To start a region, type #region , and at the end of the block of code type #endregion. The editor will now allow you to collapse this code.

#region myRegion
Console.WriteLine("Please Enter Your Age:");
string myName = Console.ReadLine();
Console.WriteLine("You Entered: " + myName);
#endregion

Listing 1-1, Example usage of Region and Endregion

Summary and Conclusions

In this tutorial we saw how the Visual C# IDE is very clever at predicting what you are going to type, and it is able to improve your productivity by reducing the amount of time spent coding. We also saw how regions and blocks can be collapsed to declutter the code window.

In the next tutorial we will have a look at the task list and see how we can use it to help plan our development.

Class Abstraction and Encapsulation

Abstract classes provide a way to force an inherited class to impliment an override method, similar to, but not the same as an interface.

Unlike an interface, abstract classes are fully functional classes, but you can force one or more methods to be overridden.

Lets say you had a theoretical vehicle class. Every vehicle must be able to steer (i.e. must have a steer() method) however different types of vehicle will have different implementation of this method. It is pointless to implement this method in the base class as the code will not be used, but dangerous to leave it empty as it could be called and the resulting vehicle will be unable to steer. By marking the method as abstract, you force any derived classes to have their own implementation of the method.

abstract class Vehicle
{
abstract public void steer();
}

Because there is no implementation of the steer method, the statement is terminated with a semi-colon. If one or more methods are marked as abstract, then the class must also be marked as abstract.

Now, each class that inherits from the Vehicle class must implement the steer method.

public class Car : Vehicle
{
public override void steer()
{
// Implement a steering wheel
}
}

public class Bike : Vehicle
{
public override void steer()
{
// Implement handlebars
}
}

public class Tank : Vehicle
{
public override void steer()
{
// Implement tracked drive steering
}
}

public class Airplane : Vehicle
{
public override void steer()
{
// Implement ailerons and rudders
}
}

This ensures that all inherited classes always have a specific implementation of the abstract method.

Encapsulation

Encapsulation is the ability for an object to hide its data and methods from those who do not need to know, and only expose data and methods that are required.

Techniques for encapsulation include class abstraction and properties. Sometimes you may not wish direct interaction with an objects data fields, for example in a bank account class you would not want to expose a balance field where it could possibly be modified without any checks or security.

Abstraction is the process of protecting the data using properties, so that any attempt to modify the data is done through the proper channels, ideally with an audit log for the bank account class.

Interfaces

In this tutorial we will look at a construct similar to a class, but not a class. An interface can be thought of as a contract between a class and a service.

Any class that implements an interface must implement all aspects of the service specified by the interface. This ensures that when you use a class that inherits from an interface you know that it implements all the required functionality.

Interfaces cannot contain constants, data fields, constructors, destructors and static members. It can only contain the signatures of methods, properties, delegates or events. All the member declarations inside interface are implicitly public. If your abstract class only provides abstract methods then you can create an interface.

It is good practice to name interfaces with a capital I and also capitalise the first letter, for example an interface called PetrolEngine would be named IPetrolEngine. This way you (and any other developers) know that it is an interface.

Although C# does not support multiple inheritance, your classes and structs can inherit from a base class as well as multiple interfaces. Let’s look at a few classes and interface examples.

interface ITestInterface
{
public void MethodToImpliment();
}

A simple interface

class TestClass : ITestInterface
{
}

Classes implement interfaces in the same way that classes inherit from base classes. Because our TestClass impliments ITestInterface, we must provide an implementation of MethodToImpliment or the compiler will throw an error.

class TestClass : ITestInterface
{
public MethodToImpliment()
{
Console.WriteLine("Test Method Called!");
}
}

You may find that you need to inherit from a base class as well as implementing an interface. This can be done by first specifying the base class, then a comma separated list of interfaces.

class TestClass : BaseClass, ITestInterface
{
public MethodToImpliment()
{
Console.WriteLine("Test Method Called!");
}
}

class TestClass : BaseClass, ITestInterface1, ITestInterface2
{
public MethodToImpliment()
{
Console.WriteLine("Test Method Called!");
}
}

Refactor Functions

If you have created a class, you can use the refactor function of Visual Studio to automatically generate an interface declaration. Simply right click on the class name, select refactor then extract interface. This will create the code for an interface and amend your class to implement it.

You can also implement an interface using refactor. If you create a skeleton class which specifies an interface you can right click the interface and select implement interface. This will generate method stubs within your class that you can implement.

Extending Interfaces

An interface can be extended in the same way that a class can be extended using inheritance. This is useful when you want to add more functionality to an interface but keep the original less-specific interface intact.

interface ITestInterface2 : ITestinterface
{
public AnotherMethodToImpliment();
}