IntroductionThe C# programming language is a modern, object-oriented language created byMicrosoft for the .NET Framework. C# (pronounced “see sharp”) builds upon some of thebest features of the major programming languages. It combines the power of C++ withthe simplicity of Visual Basic and also borrows much from Java. This results in a languagethat is easy to learn and use, robust against errors and that enables rapid applicationdevelopment. All this is achieved without sacrificing much of the power or speed, whencompared to C++.In the years following its release in 2002, C# has become the third most popularprogramming language – after Java and C/C++ – and its popularity keeps growing. It isa general-purpose programming language, so it is useful for creating a wide range of

programs. Everything from small utilities to computer games, desktop applications oreven operating systems can be built in C#. The language can also be used with ASP.NETto create web based applications.When developing in .NET, programmers are given a wide range of choice as to whichprogramming language to use. Some of the more popular .NET languages include: VB.NET,C++/CLI, F# and C#. Among these, C# is often the language of choice. Like the other .NETlanguages, C# is initially compiled to an intermediate language. This language is called theCommon Intermediate Language (CIL) and is run on the .NET Framework. A .NET programwill therefore be able to execute on any system that has that framework installed.The .NET Framework is a software framework that includes a common executionengine and a rich class library. It runs on Microsoft Windows and is therefore only usedfor writing Windows applications. However, there are also cross-platform ports available,the the two largest being Mono1 and DotGNU.2 These are both open source projectsthat allow .NET applications to be run on other platforms, such as Linux, Mac OS X andembedded systems.

12

http://www.mono-project.comhttp://www.dotgnu.org

xix

Chapter 1

Hello WorldChoosing an IDETo begin coding in C# you need an Integrated Development Environment (IDE) thatsupports the Microsoft .NET Framework. The most popular choice is Microsoft’s ownVisual Studio.1 This IDE is also available for free as a light version called Visual StudioExpress, which can be downloaded from Microsoft’s website.2The C# language has undergone a number of updates since the initial release ofC# 1.0 in 2002. At the time of writing, C# 5.0 is the current version which was releasedin 2012. Each version of the language corresponds to a version of Visual Studio, soin order to use the features of C# 5.0 you need Visual Studio 2012 or Visual StudioExpress 2012.

Creating a projectAfter installing the IDE, go ahead and launch it. You then need to create a new project,which will manage the C# source files and other resources. To display the New Projectwindow go to File ➤ New ➤ Project in Visual Studio, or File ➤ New Project in VisualStudio Express. From there select the Visual C# template type in the left frame. Thenselect the Console Application template in the right frame. At the bottom of the windowyou can configure the name and location of the project if you want to. When you are doneclick OK and the project wizard will create your project.You have now created a C# project. In the Solution Explorer pane (View ➤Solution Explorer) you can see that the project consists of a single C# source file (.cs)that should already be opened. If not, you can double-click on the file in the SolutionExplorer in order to open it. In the source file there is some basic code to help you getstarted. However, to keep things simple at this stage go ahead and simplify the codeinto this.

12

http://www.microsoft.com/visualstudiohttp://www.microsoft.com/express

1

CHAPTER 1 ■ Hello World

class MyApp{static void Main(){}}The application now consists of a class called MyApp containing an emptyMain method, both delimited by curly brackets. The Main method is the entry pointof the program and must have this format. The casing is also important since C# iscase-sensitive. The curly brackets delimit what belongs to a code entity, such as a classor method, and they must be included. The brackets, along with their content, is referredto as a code block, or just a block.

Hello WorldAs is common when learning a new programming language the first program to write isone that displays a “Hello World” text string. This is accomplished by adding the followingline of code between the curly brackets of the Main method.System.Console.WriteLine("Hello World");This line of code uses the WriteLine method which accepts a single stringparameter delimited by double quotes. The method is located inside the Console class,which belongs to the System namespace. Note that the dot operator (.) is used to accessmembers of both namespaces and classes. The statement must end with a semicolon, asmust all statements in C#. Your code should now look like this.class MyApp{static void Main(){System.Console.WriteLine("Hello World");}}

IntelliSenseWhen writing code in Visual Studio a window called IntelliSense will pop-up whereverthere are multiple predetermined alternatives from which to choose. This window isincredibly useful and can be brought up manually by pressing Ctrl + Space. It gives youquick access to any code entities you are able to use within your program, including theclasses and methods of the .NET Framework along with their descriptions. This is a verypowerful feature that you should learn to make good use of.

2

Chapter 2

Compile and RunVisual Studio compilationWith the Hello World program completed, the next step is to compile and run it. To doso open up the Debug menu and select Start Without Debugging, or simply pressCtrl + F5. Visual Studio will then compile and run the application which displays thestring in a console window.The reason why you do not want to choose the Start Debugging command (F5) isbecause the console window will then close as soon as the program has finished executing.

Console compilationIf you did not have an IDE such as Visual Studio, you could still compile the program aslong as you have the .NET Framework installed. To try this, open up a console window(C:\Windows\System32\cmd.exe) and navigate to the project folder where the sourcefile is located. You then need to find the C# compiler called csc.exe, which is located ina path similar to the one shown below. Run the compiler with the source filename as anargument and it will produce an executable in the current folder.

If you try running the compiled program it will show the same output as that createdby Visual Studio.

C:\MySolution\MyProject> Program.exeHello World

3

CHAPTER 2 ■ Compile and Run

CommentsComments are used to insert notes into the source code. C# uses the standard C++ commentnotations, with both single-line and multi-line comments. They are meant only to enhancethe readability of the source code and have no effect on the end program. The single-linecomment begins with “//” and extends to the end of the line. The multi-line comment mayspan multiple lines and is delimited by “/*” and “*/”.

// single-line comment

/* multi-linecomment */

In addition to these, there are two documentation comments. One single-linedocumentation comment that starts with “///”, and one multi-line documentationcomment that is delimited by “/**” and “*/”. These comments are used when producingclass documentation.

VariablesVariables are used for storing data during program execution.

Data typesDepending on what data you need to store there are several different kinds of data types.The simple types in C# consist of four signed integer types and four unsigned, threefloating-point types as well as char and bool.

Data Type

Size (bits)

sbyte

8

short

16

int

32

long

64

byte

8

ushort

16

uint

32

ulong

64

float

32

double

64

decimal

DescriptionSigned integers

Unsigned integers

Floating-point numbers

128

char

16

bool

4

Unicode characterBoolean value

5

CHAPTER 3 ■ Variables

DeclarationIn C#, a variable must be declared (created) before it can be used. To declare a variableyou start with the data type you want it to hold followed by a variable name. The namecan be almost anything you want, but it is a good idea to give your variables names thatare closely related to the value they will hold.

int myInt;

AssignmentA value is assigned to the variable by using the equals sign, which is the assignmentoperator (=). The variable then becomes defined or initialized.

myInt = 10;

The declaration and assignment can be combined into a single statement.

int myInt = 10;

If multiple variables of the same type are needed there is a shorthand way ofdeclaring or defining them by using the comma operator (,).

int myInt = 10, myInt2 = 20, myInt3;

Once a variable has been defined (declared and assigned) it can be used byreferencing the variable’s name.

System.Console.Write(myInt); // 10

Integer typesThere are four signed integer types that can be used depending on how large a numberyou need the variable to hold.

In addition to the standard decimal notation, integers can also be assigned usinghexadecimal notation.

int myHex = 0xF; // hexadecimal (base 16)

Floating-point typesThe floating-point types can store real numbers with different levels of precision.Constant floating-point numbers in C# are always kept as doubles, so in order to assignsuch a number to a float variable an “F” character needs to be appended to convert thenumber to the float type. The same applies to the “M” character for decimals.

A more common and useful way to convert between data types is to use an explicitcast. An explicit cast is performed by placing the desired data type in parentheses beforethe variable or constant that is to be converted. This will convert the value to the specifiedtype, in this case float, before the assignment occurs.

myFloat = (float)myDecimal; // explicit cast

The precisions shown above refer to the total number of digits that the types canhold. For example, when attempting to assign more than 7 digits to a float, the leastsignificant ones will get rounded off.

myFloat = 12345.6789F; // rounded to 12345.68

Floating-point numbers can be assigned using either decimal or exponentialnotation.

myDouble = 3e2; // 3*10^2 = 300

7

CHAPTER 3 ■ Variables

Char typeThe char type can contain a single Unicode character delimited by single quotes.

char c = '3'; // Unicode char

Bool typeThe bool type can store a Boolean value, which is a value that can only be either true orfalse. These values are specified with the true and false keywords.

bool b = true; // bool value

Variable scopeThe scope of a variable refers to the code block within which it is possible to use thatvariable without qualification. For example, a local variable is a variable declared withina method. Such a variable will only be available within that method’s code block, afterit has been declared. Once the scope of the method ends, the local variable will bedestroyed.

int main(){int localVar; // local variable}

In addition to local variables, C# has field and parameter type variables, which willbe looked at in later chapters. However, C# does not have global variables, as for exampledoes C++.

8

Chapter 4

OperatorsOperators are used to operate on values. They can be grouped into five types: arithmetic,assignment, comparison, logical and bitwise operators.

Arithmetic operatorsThe arithmetic operators include the four basic arithmetic operations, as well as themodulus operator (%) which is used to obtain the division remainder.

Notice that the division sign gives an incorrect result. This is because it operates ontwo integer values and will therefore round the result and return an integer. To get thecorrect value, one of the numbers needs to be converted into a floating-point number.

x = 3 / (float)2; // 1.5

Assignment operatorsThe second group is the assignment operators. Most importantly, the assignmentoperator (=) itself, which assigns a value to a variable.

Combined assignment operatorsA common use of the assignment and arithmetic operators is to operate on a variable andthen to save the result back into that same variable. These operations can be shortenedwith the combined assignment operators.

9

CHAPTER 4 ■ Operators

int xxxxxx

= 0;+= 5;-= 5;*= 5;/= 5;%= 5;

//////////

xxxxx

=====

x+5;x-5;x*5;x/5;x%5;

Increment and decrement operatorsAnother common operation is to increment or decrement a variable by one. This can besimplified with the increment (++) and decrement (--) operators.

x++; // x = x+1;x--; // x = x-1;

Both of these operators can be used either before or after a variable.

The result on the variable is the same whichever is used. The difference is thatthe post-operator returns the original value before it changes the variable, while thepre-operator changes the variable first and then returns the value.

x = 5; y = x++; // y=5, x=6x = 5; y = ++x; // y=6, x=6

Comparison operatorsThe comparison operators compare two values and return either true or false. They aremainly used to specify conditions, which are expressions that evaluate to either trueor false.

Logical operatorsThe logical operators are often used together with the comparison operators. Logical and(&&) evaluates to true if both the left and right side are true, and logical or (||) evaluates totrue if either the left or right side is true. The logical not (!) operator is used for invertinga Boolean result. Note that for both “logical and” and “logical or” the right side of theoperator will not be evaluated if the result is already determined by the left side.

Bitwise operatorsThe bitwise operators can manipulate individual bits inside an integer. For example, thebitwise and (&) operator makes the resulting bit 1 if the corresponding bits on both sidesof the operator are set.

Operator precedentsIn C#, expressions are normally evaluated from left to right. However, when an expressioncontains multiple operators, the precedence of those operators decides the order inwhich they are evaluated.

11

CHAPTER 4 ■ Operators

Pre

Operator

Pre

Operator

1

++ -- ! ~

7

&

2

*/%

8

^

3

+-

9

|

4

<< >>

10

&&

5

< <= > >=

11

||

6

== !=

12

= op=

For example, logical and (&&) binds weaker than relational operators, which in turnbind weaker than arithmetic operators.

bool x = 2+3 > 1*4 && 5/5 == 1; // true

To make things clearer, parentheses can be used to specify which part of the expressionwill be evaluated first. Parentheses have the highest precedence of all operators.

bool x = ((2+3) > (1*4)) && ((5/5) == 1); // true

12

Chapter 5

StringThe string data type is used to store string constants, which are delimited by double quotes.

string a = "Hello";

String concatenationThe plus sign is used to combine two strings. It is known as the concatenation operator(+) in this context. It also has an accompanying assignment operator (+=), which appendsa string to another and creates a new string.

string b = a + " World"; // Hello Worlda += " World";// Hello World

Escape charactersA statement can be broken up across multiple lines, but a string constant must be ona single line. In order to divide it, the string constant has to first be split up using theconcatenation operator.

string c= "Hello " +"World";

To add new lines into the string itself, the escape character “\n” is used.

string c = "Hello\nWorld";

This backslash notation is used to write special characters, such as the backslashitself or a double-quote. Among the special characters is also a Unicode characternotation for writing any character.

13

CHAPTER 5 ■ String

Character

Meaning

Character

Meaning

\n

newline

\f

form feed

\t

horizontal tab

\a

alert sound

\v

vertical tab

\’

single quote

\b

backspace

\”

double quote

\r

carriage return

\\

backslash

\0

null character

\uFFFF

Unicode character (4-digit hex number)

Escape characters can be ignored by adding an “@” symbol before the string. This iscalled a verbatim string and can for example be used to make file paths more readable.

String compareThe way to compare two strings is simply by using the equal to operator. This will notcompare the memory addresses, as in some other languages such as Java.

bool c = (a == b); // true

String membersThe string class has a lot of useful members. For example, methods like Replace, Insertand Remove. An important thing to note is that there are no methods for changing a string.Methods that appear to modify a string actually always return a completely new string.This is because the string class is immutable. The content of a string variable cannot bechanged, unless the whole string is replaced.

StringBuilder classStringBuilder is a mutable string class. Because of the performance cost associated withreplacing a string, the StringBuilder class is a better alternative when a string needs tobe modified many times.

System.Text.StringBuilder sb = newSystem.Text.StringBuilder("Hello");

The class has several methods that can be used to manipulate the actual content ofa string, such as: Append, Remove and Insert.

To convert a StringBuilder object back into a regular string, the ToString methodis used.

string s = sb.ToString(); // Bye World

15

Chapter 6

ArraysAn array is a data structure used for storing a collection of values that all have the samedata type.

Array declarationTo declare an array, a set of square brackets is appended to the data type the array willcontain, followed by the array’s name. An array can be declared with any data type and allof its elements will then be of that type.

int[] x; // not int x[]

Array allocationThe array is allocated with the new keyword, followed again by the data type and a set ofsquare brackets containing the length of the array. This is the fixed number of elementsthat the array can contain. Once the array is created, the elements will automatically beassigned to the default value for that data type.

int[] x = new int[3];

Array assignmentTo fill the array elements they can be referenced one at a time and then assigned values.An array element is referenced by placing the element’s index inside square brackets.Notice that the index for the first element starts with zero.

x[0] = 1;x[1] = 2;x[2] = 3;

17

CHAPTER 6 ■ Arrays

Alternatively, the values can be assigned all at once by using a curly bracket notation. Thenew keyword and data type may optionally be left out if the array is declared at the same time.

int[] y = new int[] { 1, 2, 3 };int[] z = { 1, 2, 3 };

Array accessOnce the array elements are initialized, they can be accessed by referencing the elements’indexes inside the square brackets.

System.Console.Write(x[0] + x[1] + x[2]); // 6

Rectangular arraysThere are two kinds of multi-dimensional arrays in C#: rectangular and jagged.A rectangular array has the same length of all sub-arrays and separates the dimensionsusing a comma.

string[,] x = new string[2, 2];

As with single-dimensional arrays, they can either be filled in one at a time or all atonce during the allocation.

Switch statementThe switch statement checks for equality between either an integer or a string and a seriesof case labels, and then passes execution to the matching case. The statement can containany number of case clauses and may end with a default label for handling all other cases.

Note that the statements after each case label are not surrounded by curly brackets.Instead, the statements end with the break keyword to break out of the switch. Unlike manyother languages, case clauses in C# must end with a jump statement, such as break. This meansthat the break keyword cannot be left out to allow the execution to fall-through to the nextlabel. The reason for this is that unintentional fall-throughs is a common programming error.

Goto statementTo cause a fall-through to occur, this behavior has to be explicitly specified using the gotojump statement followed by a case label. This will cause the execution to jump to that label.

case 0: goto case 1;

Goto may be used outside of switches to jump to a label within the same method’sscope. Control may then be transferred out of a nested scope, but not into a nested scope.However, using goto in this manner is discouraged since it can become difficult to followthe flow of execution.

goto myLabel;// ...myLabel:

Ternary operatorIn addition to the if and switch statements there is the ternary operator (?:). This operatorcan replace a single if/else clause that assigns a value to a specific variable. The operatortakes three expressions. If the first one is evaluated to true then the second expression isreturned, and if it is false, the third one is returned.

LoopsThere are four looping structures in C#. These are used to execute a specific code blockmultiple times. Just as with the conditional if statement, the curly brackets for the loopscan be left out if there is only one statement in the code block.

While loopThe while loop runs through the code block only if its condition is true, and will continuelooping for as long as the condition remains true. Note that the condition is only checkedat the beginning of each iteration (loop).

int i = 0;while (i < 10) { System.Console.Write(i++); } // 0-9

Do-while loopThe do-while loop works in the same way as the while loop, except that it checks thecondition after the code block and will therefore always run through the code block atleast once. Bear in mind that this loop ends with a semicolon.

int j = 0;do { System.Console.Write(j++); } while (j < 10); // 0-9

For loopThe for loop is used to go through a code block a specific number of times. It uses threeparameters. The first parameter initializes a counter and is always executed once, beforethe loop. The second parameter holds the condition for the loop and is checked beforeeach iteration. The third parameter contains the increment of the counter and is executedat the end of each iteration.