Anda di halaman 1dari 50

C# TUTORIAL

FOR BEGINNERS
Learn the fundamentals of the
C# programming language

Stefanos Arapakis www.eurekalearn.net

V1.0

2|

FOREWARD

Hi. Im Stefanos Arapakis, and I wrote this tutorial to help beginners learn the fundamentals of the C# programming
language.
Programming is a really great career. You can build software that makes the lives of people easier, more productive and
even fun. However, learning to program is like learning to ride a bike. It is difficult in the beginning, but with patience,
persistence and practice you eventually learn how to ride. Take the time to really master the basics first. This will ensure
that you build a solid foundation for the rest of your programming career.
If you prefer to learn by watching and doing, then visit me at www.eurekalearn.net and sign up for my C# Tutorial for
Beginners Video Course.
I wish you all the best and may this be your start to a great career.
Stefanos Arapakis
Software Developer and founder of eurekalearn.net

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

3|

Contents
C# TUTORIAL FOR BEGINNERS ........................................................................................................................................................................ 1
Foreward ........................................................................................................................................................................................................................ 2
Introduction........................................................................................................................................................................................................................ 7
1.Variables ........................................................................................................................................................................................................................... 8
Comments ..................................................................................................................................................................................................................... 8
Variables ......................................................................................................................................................................................................................... 8
Declaring Variables .................................................................................................................................................................................................... 8
Constants ....................................................................................................................................................................................................................... 9
Conversions................................................................................................................................................................................................................... 9
Implicit Conversion............................................................................................................................................................................................... 9
Explicit Conversion .............................................................................................................................................................................................10
Nullables ......................................................................................................................................................................................................................10
The ?? operator ....................................................................................................................................................................................................11
2. Operators......................................................................................................................................................................................................................12
Arithmetic Operators .........................................................................................................................................................................................12
Relational Operators ..........................................................................................................................................................................................13
Logical Operators................................................................................................................................................................................................13
Assignment Operators ......................................................................................................................................................................................14
Increment Decrement Operators ..................................................................................................................................................................14
3.Flow Control .................................................................................................................................................................................................................15
Branching .....................................................................................................................................................................................................................15

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

4|

The if statement ...............................................................................................................................................................................................15


The switch statement .....................................................................................................................................................................................16
Looping.........................................................................................................................................................................................................................17
The for loop .......................................................................................................................................................................................................17
The while loop ..................................................................................................................................................................................................18
The do while loop............................................................................................................................................................................................19
4. Classes ...........................................................................................................................................................................................................................21
Objects ..........................................................................................................................................................................................................................21
Fields..............................................................................................................................................................................................................................21
Properties.....................................................................................................................................................................................................................22
Methods and Functions .........................................................................................................................................................................................23
Access Specifier ...................................................................................................................................................................................................23
Return type ............................................................................................................................................................................................................23
Method Name ......................................................................................................................................................................................................23
Parameters .............................................................................................................................................................................................................23
Passing Arguments ..................................................................................................................................................................................................24
By Value ..................................................................................................................................................................................................................24
By Reference .........................................................................................................................................................................................................24
Method Overloading (compile time polymorphism/early binding) .....................................................................................................25
5. Inheritance ...................................................................................................................................................................................................................27
Multiple Inheritance ...........................................................................................................................................................................................28
Method overriding (run time polymorphism/late binding) .....................................................................................................................28
6. Composition ................................................................................................................................................................................................................31

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

5|

Composition vs Inheritance ..................................................................................................................................................................................32


7. Interfaces ......................................................................................................................................................................................................................33
8. Abstract Classes .........................................................................................................................................................................................................35
Abstract Methods ...............................................................................................................................................................................................35
Non abstract methods ......................................................................................................................................................................................35
Abstract class vs Interface .....................................................................................................................................................................................36
When to use abstract classes and interfaces .................................................................................................................................................36
Namespaces .....................................................................................................................................................................................................................38
Arrays ..................................................................................................................................................................................................................................39
Single Dimensional Arrays ....................................................................................................................................................................................39
Multi-dimensional arrays .......................................................................................................................................................................................40
Two dimensional arrays ....................................................................................................................................................................................40
Jagged Arrays.............................................................................................................................................................................................................41
Limitations of Arrays ..........................................................................................................................................................................................42
Collections.........................................................................................................................................................................................................................43
Iterating a collection ..........................................................................................................................................................................................43
ArrayList........................................................................................................................................................................................................................43
Stack...............................................................................................................................................................................................................................44
Queue............................................................................................................................................................................................................................44
Generics .............................................................................................................................................................................................................................46
Decreased Performance ...................................................................................................................................................................................46
Generic Collections ........................................................................................................................................................................................................47
List...................................................................................................................................................................................................................................47

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

6|

Dictionary.....................................................................................................................................................................................................................48
Exception Handling .......................................................................................................................................................................................................49

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

7|

Introduction
Source code is the set of instructions that a programmer writes which tell the computer what operations to
perform.
There are various programming languages that we can use to write the source code: Java, C, C++, VB.NET, C#.
C# (pronounced see sharp) is a simple, modern, object oriented programming language developed by
Microsoft.
C# is a well established, popular programming language and it is used in the creation of a wide variety of
software - desktop applications, websites, mobile applications and web services.

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

8|

1.Variables
COMMENTS
In your code, you may want to provide notes or explanations about your code. This is purely information for you
and other programmers and it is ignored when the program is executed.
The syntax for comments is:
//

This is a single line comment

/*
This is a block comment
All the content in this block is commented
*/

VARIABLES
A variable is a reference to a storage location in memory. We use variables to assign values to memory, and
then retrieve values from memory.
Every variable has a data type which determines what value can be stored in memory. The most common are:
int

- used for zero, positive and negative numbers (but no fractions). eg. -1, 0, 1

decimal

- used for zero, positive and negative numbers and also fractions. eg. -1.5, 0, 1, 2.5

string

- used for text eg. hello

bool

- used for true or false

DateTime

- used for date/time

DECLARING VARIABLES
We declare variables in the following way:
<data type> <identifier> <optional value>

E XAMPLES
int i;
i = 10;

//int is the data type. i is the identifier(name) of the variable.


//Variable i is declared/defined, but it has no value yet
//Variable i now has the value 10

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

9|

int j = 5;

//Variable j is declared and initialized with value 5

string s = "hello";
string t = "john";
decimal d = 105.25M;
bool b = true;
DateTime dte = DateTime.Now;

CONSTANTS
A constant is a variable that is initialized with a value and cannot change value after it is initialized.
We declare constants in the following way:
const <data type> <identifier> = <value>

E XAMPLES
const int iMonth = 10;

//This is valid. A const is declared and initialized with a value.

iMonth = 12;

//This is INVALID because a const cannot be modified.

const int jYear;

//This is INVALID because there is no value. It will not compile

CONVERSIONS
When we declare a variable, we specify its data type and give it a value. There are cases however where we need
to change the data type of the value. This is called conversion.
Conversion is commonly used in cases where we copy the value of one variable to another variable.
There are 2 types of conversion:

Implicit Conversion
The C# compiler automatically (without the intervention of the programmer) tries to convert one data type to
another data type.

E XAMPLES
int x = 10;

//x is a 32 bit integer. This means that it can hold a number up to a 2147483647

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

10 |

long y = x;

//y is a 64 bit integer. This means that it can hold bigger numbers than an
integer.
//Because we are assigning a smaller data type to a bigger data type, there is no
loss of precision.

Explicit Conversion
The programmer needs to specify to what data type to convert the value to. This can be done using the
Convert method.

E XAMPLES
int i = 100;
string s = i;

//INVALID. i is an int. s is a string.


//Cannot assign an int to a string. It will not compile.

string t = Convert.ToString(i); //Valid. int is converted to string

decimal d = 100.34M;
int j = Convert.ToInt32(d);

//Valid. We convert from int to decimal.


//However we LOOSE some of the value when converting from
//decimal to int
//Reason: an int does not store fractions, so when converting
//from decimal to int, we loose the 0.34
//So, the value of j after the conversion is 100

NULLABLES
Value type variables such as int, decimal and bool cannot be assigned null values. Null loosely means to have no
value.
There are cases however that we need to force a variable to accept null values. Ie. we need to make the variable
nullable.
The syntax to make a variable nullable is:
<data type>? <identifier> <optional value>
The ability to be able to assign null to int, decimal and bool is useful when dealing with databases. When
reading data from the database, an element might not have a value. This element is returned as a null which by
default cannot be assigned to a variable. In order to force the variable to accept a null value we make the
variable nullable using the ? operator.

E XAMPLE

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

11 |

int i = null;

//i is not a nullable type and therefore cannot be assigned a null value.
//this will not compile

int? j = null;

//j has been made nullable and is assigned a null value.

The ?? operator
When testing if a variable is null, we can use an if statement. A shorthand approach is to use the null coalescing
operator ??

E XAMPLE
int? j = null;

//j has been made nullable and is assigned a null value.

//A********************************
int? k;
if (j == null)
{
k = 5;
}
else
{
k = j;
}
//A can be replaced with the one line below
int k = j ?? 5;
//if j is null, then return 5 else return j

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

12 |

2. Operators
Operators are symbols that allow you to perform certain actions/manipulations on data. The data elements on
which the actions are performed are called operands.
There are 3 types of operators:

Arithmetic Operators
Arithmetic operators take two operands and perform a mathematical calculation on them.
+
*
/
%

//Addition
//Subtraction
//Multiplication
//Division
//Modulus

E XAMPLES
int i = 10;
int j = 20;
int k = i + j;

int x = 4;
int y = 3;
int z = x - y;
int a = 4;
int b = 3;
int c = a * b;
int
int
int
int
int

d
e
f
g
h

=
=
=
=
=

14;
7;
0;
d / e;
d / f;

//Addition
//+ is the operator
//i is an operand
//j is an operand
//the value of k is 30

//Subtraction
//The value of z is 1.

//Multiplication.
//The value of c is 12

//Division. The value of g is 2.


//INVALID.
//We are trying to perform 14/0
//In mathematics it is impossible to divide by zero!
//The program will compile, but while it is running it will crash.
//This is a very common programming error and you need to avoid it.

int q = 15;
int r = 2;

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

13 |

int s = q % r;

//Modulus. The value of s is 1.


//15 can be divided by 7 two times which gives 14.
//The remainder is (15-14) = 1

Relational Operators
Relational operators compare values to each other and return a Boolean value (i.e. either true or false).
<
<=
>
>=

//Less than operator


//Less than or equal to operator
//Greater than operator
//Greater than or equal to operator

==

//Equality operator. Checks if two operands are equal.


//If they are equal, the result is true.
//if they are not equal, the result is false

!=

//Inequality operator. Checks if two operands are not equal.


//If they are not equal, the result is true.
//If they are equal, the result is false

E XAMPLES
int i = 5;
int j = 7;
int k = 7;
bool
bool
bool
bool
bool
bool
bool
bool

b1
b2
b3
b4
b5
b6
b7
b8

=
=
=
=
=
=
=
=

i
i
j
j
j
i
j
j

< j;
<= j;
< k;
<= k;
> i;
> j;
> k;
>= k;

//b1
//b2
//b3
//b4
//b5
//b6
//b7
//b8

is
is
is
is
is
is
is
is

true;
true;
false;
true;
true;
false;
false;
true;

bool b9 = j == k;
bool b10 = i == k;
bool b11 = j != k;

//b9 is true;
//b10 is false;
//b11 is false;

bool b12 = i != k;

//b12 is true;

Logical Operators
&&
||
!

//Logical AND If
//Logical OR If
//Logical NOT - If
If

expression
expression
the result
the result

A is true and expression B is true, then it returns true


A is true or expression B is true, then it returns true
it true, then it changes the result to false.
is false, then it changes the result to true.

E XAMPLE
int i = 10;
int j = 20;
int k = 30;

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

14 |

if ((i == 10) && (j == 20))


{
}

//both expressions are true.


//returns true

if ((i == 10) && (j == 40))


{
}

//both expressions are not true.


//returns false

if ((i == 10) || (j == 40))


{
}

//one of the expressions is true (i==10)


//returns true

if ((i == 15) || (j == 40))


{
}

//there is not even one expression that is true


//returns false

if (i == 10)
{
}

//returns true

if (!(i == 10))
{
}

//i==10 is true, but due to the logical not operator !


//the result is changed to false

if (i == 15)
{
}

//returns false

if (!(i == 15))
{
}

//i==15 is false, but due to the logical not ope


//the result is changed to true

Assignment Operators
Assignment operators assign a new value to a variable.
=
+=
-=
*=
/=

//Assignment operator
//Addition assignment operator
//Subtraction assignment operator
//Multiplication assignment operator
//Division assignment operator

Increment Decrement Operators


++
--

//The increment operator increases its operand by 1.


//The decrement operator decreases its operand by 1.

Increment and decrement operators can appear before or after the operand.

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

15 |

3.Flow Control
Flow control refers to the order of execution of C# code. The normal flow of execution is line by line, from the
top to the bottom.
There are two ways that we can change the flow of execution of code: Branching and Looping

BRANCHING
Branching evaluates a condition and then determines what code to execute next. This can be done using the if
statement or the switch statement.

The if statement
The if statement is used to make a logical decision.
In other words, we use the if statement to determine if certain code should be executed or not.
The syntax of the if statement is as follows:
if (<expression>)
{
//this statement will execute if the above expression is true
}
else if (<expression>)
{
//this statement will execute if the above expression is true
}
else{
//if all the expressions above evaluate to false, then this statement will be executed.
}

E XAMPLE
Console.WriteLine("Enter your age");
string sAge = Console.ReadLine();
int iAge = Convert.ToInt16(sAge);

//Ask for input from the user


//Read the user input
//Convert the string to an integer
//so that we can compare numbers

if (iAge >= 18)


//We evaluate if the user is >= 18
{
//If it is true that the user is >= 18 then this line will execute
Console.WriteLine("You are old enough to enter");
}
else if (iAge >= 12)
//At this point we know that this user is NOT >= 18.
//We evaluate if he is >= 12
{
//This line is executed if the user is >= 12

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

16 |

Console.WriteLine("You can enter but have only limited access");


}
else
{
//At this point we know the following:
//The user is NOT >= 18
//The user is NOT >= 12
//i.e. The user is < 12
//So, for all users < 12, the message is displayed: "You are too young to enter"
Console.WriteLine("You are too young to enter");
}

The switch statement


The switch statement is used to make a logical decision.
In other words, we use the switch statement to determine if certain code should be executed or not.
The switch statement is similar to the if statement. However, the switch statement can only evaluate a
constant expression. It cannot be used to evaluate if a number is greater than or less than.
The syntax of the switch statement is as follows:
switch(<expression>)
//the expression must be a string or an integer
{
case <constant-expression>:
//this statement will execute if the above constant-expression is true
break; //this will exit out of the switch statement
default:
//this statement will execute if none of the above constant-expressions are true
break;
}

E XAMPLE
Console.WriteLine("Enter a number from 1 to 3 ?");
string sInput = Console.ReadLine();
int iInput = Convert.ToInt16(sInput);
switch (iInput)
{
case 1:
Console.WriteLine("You win a car");
break;

//Ask for input from the user


//Read the user input
//Convert the string to an integer

//This line will execute if the user entered 1

case 2:
Console.WriteLine("You win a scooter");//This line will execute if the user entered 2
break;
case 3:
Console.WriteLine("You win a bike");

Copyright Stefanos Arapakis 2014

//This line will execute if the user entered 3

www.eurekalearn.net

17 |

break;
default:
Console.WriteLine("Sorry. You don't win anything"); //This line will execute if the
//user entered any other number
break;
}

LOOPING
A loop is used to run a statement(s) repeatedly.

The for loop


The for loop is the most common loop. It is used when you know in advance how many times you want the
loop to occur.
The syntax of the for loop is as follows:
for (<initializer>; <condition>; <iterator>)
{
//This code is executed many times
}

<initializer>

- specify the start value.

<condition>

- the loop will occur while the condition is true.

<iterator> - specify what must be done to the variable initialized after each loop.

E XAMPLE
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i.ToString());
}
//Explanation
//int i = 0

//i < 10
//i++

we initialize a variable called i with the value 0.


i.e. our loop starts from 0.
we loop while the condition is true. i.e we loop while i < 10
after each loop, we increment i by 1.

//So, this loop will run 10 times.


//The output will be:
//0
//1
//2
//3

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

18 |

//4
//5
//6
//7
//8
//9
//*********************************************************************************
//To loop through all the elements in the array:
int[] i = new int[] { 10, 20, 30, 40, 50 }; //i is an array of integers and holds 5 values
//This example will loop 5 times because i.Length is 5
//ie. i has 5 elements in its array
for (int x = 0; x < i.Length; x++)
{
Console.WriteLine(i[x]);
//i is the array
//x is the index value.
//ie. when x is 0, then we access the first element at i[0] and the output is 10
//ie. when x is 1, then we access the second element at i[1] and the output is 20
//ie. when x is 2, then we access the third element at i[2] and the output is 30
//ie. when x is 3, then we access the fourth element at i[3] and the output is 40
//ie. when x is 4, then we access the fifth element at i[4] and the output is 50
}

The while loop


The while statement executes statement(s) while the specified condition evaluates to true.
The syntax of the while statement is as follows:
while (<condition>)
{
//This code is executed while the condition is true
}

Just like the for loop, the while loop can also be used when we know in advance how many times we want to
loop.

E XAMPLE
int i = 0;
//initialize a variable i to value 0.
while (i < 10)
//evaluate if i < 10
{
Console.WriteLine(i.ToString());
//if < 10 is true, then we output i
i++;
//increment i.
}
//Explanation
//This loop will execute 10 times.
//The output will be
//0

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

19 |

//1
//2
//3
//4
//5
//6
//7
//8
//9

In practice however, a while statement is usually used when we do not know in advance how many times we
want to loop. An example is when we are reading a csv file that we need to import into our database. When we
start reading the csv file we do not know at the beginning how many lines there are in the csv file. So we read
while we are not at the end of the file.

E XAMPLE
//Dont worry if you dont understand all the code below.
//Just understand the concept:
//We loop while we are not at the end of the file
string sFileName = "C:\file1.csv";
FileInfo fileIn = new FileInfo(sFileName);
StreamReader reader = fileIn.OpenText();
string[] lineIn;
while (!reader.EndOfStream)
{
lineIn = reader.ReadLine().Split(',');
}
reader.Close();

The do while loop


The do while loop is similar to the while loop. The difference is as follows:
A while loop can execute zero or more times.
A do while loop can execute one or more times. i.e. a do while loop will always execute at least one time,
regardless of whether the expression evaluates to false or not.
The syntax of the do while statement is as follows:
do
{
//This code is executed at least once, and thereafter while the condition is true
} while (<condition>)

E XAMPLE

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

20 |

int i = 0;
//Initialize a variable i to value 0.
do
{
Console.WriteLine(i.ToString());
//Run this statement at least once.
} while (i < 0);
//Evaluate if this expression is true.
//If the expression is true, then run the above statement again.
//If the expression is false, then exit the do while loop.

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

21 |

4. Classes
Classes are a very important topic and are the foundation of OOP (Object Oriented Programming).
One of the main reasons of using OOP is re-usability.
A class is a blueprint or template. i.e. it contains info of how an object should be built.
An object is something that is actually created based on the class (or blueprint).
Think of the architectural drawing of your house as the class. Your actual house that you live in is the object.
The syntax for declaring a class is:
<access specifier> class <name>
{
//Fields
//Properties
//Methods
//Events
}

E XAMPLE
public class Person
{
}

OBJECTS
We create an object based on a class. This is called creating an instance of a class.
The syntax for creating an object is:
<class name> <object name> = new <class name> ();

E XAMPLE
Person john = new Person();

A class contains members called fields, properties and methods.

FIELDS

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

22 |

A field is a variable that is declared directly in a class. It is generally accepted best practice to declare fields with
the private access specifier. Thus, the field is used to hold data about the class, but is only accessible internally
within the class, and not from the outside.
The syntax to declare a field is:
<access specifier> <data type> <identifier> <optional value>

E XAMPLE
private string _firstName = "";

PROPERTIES
A property is an attribute of the class and is accessible by external code as well as internally within the class. It is
used by external code to read/write data to the class. Generally, the property will internally use the private
declared field to store its data for the property.
The syntax to declare a property is:
<access specifier> <data type> <identifier>
{
get
{
return <field>
}
set
{
<field> = value;
}
}

E XAMPLE
private string _firstName = ""; //This is the private field: accessible internally only
//This is the property: accessible externally and internally
public string FirstName
{
get
{
return _firstName;
//read the value from the field
}
set
{
_firstName = value;
//save the value to the field
}
}

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

23 |

METHODS AND FUNCTIONS


A method is an action that the class can perform. It is used by external code to pass data into the class, perform
actions and retrieve data from the class.
The syntax to define a method is:
<access specifier> <return type> <method name> (<optional parameters>)
{
//method code
}

Access Specifier
The access specifier determines the accessibility of a method or variable. There are 5 access specifiers:
public

- the method can be accessed from anywhere. This is the least restrictive access specifier.

private

- the method can only be accessed from within the same class. This is the most
restrictive access specifier.

protected

- the method can be accessed from within the same class and also from derived classes.

internal

- the method can be accessed within the same assembly, but not from another assembly.

protected internal - the method can be accessed within the same class and derived classes, and within the

same assembly.

Return type
A method may return a value. If it returns a value we specify the data type to be returned. If the method does
not return a value, then we specify void.

Method Name
Specify a name to identify the method.

Parameters
Parameters are variables that are part of the method signature. They allow data to be inputted into the method.
Parameters are optional. We declare parameters the same way we declare variables. i.e. we specify the data type
and the parameter name. If there is more than one parameter, we separate them by the use of the comma.

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

24 |

E XAMPLE
//Public - accessible internally and externally
//Method Name: GetFullName
//No parameters
//Returns a string
public string GetFullName()
{
return _firstName + " " + _lastName;
}
//Public - accessible internally and externally
//Method Name: GetAge
//Accepts 1 parameter of data type: DateTime.
//Returns a TimeSpan
public TimeSpan GetAge(DateTime dateOfBirth)
{
return DateTime.Now.Subtract(dateOfBirth);
}

PASSING ARGUMENTS
An argument is a variable that we pass into a method.
Arguments can be passed to a method either by value or by reference.

By Value
By default all arguments are passed by value in C#.
When an argument is passed by value to a method, the method cannot change the value of the argument
outside of the method.

By Reference
Arguments are only passed by reference in C# if you use the ref or out keyword.
When an argument is passed by reference to a method using the ref keyword, the method can change the
value of the argument outside of the method.
When a method is passed by reference to a method using the out keyword, the method must change the value
of the argument outside of the method.

E XAMPLE
public class Multiplier
{
//Method 1 - pass an argument by value

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

25 |

public void MultiplyBy2(int number)


{
number = number * 2;
}
//Method 2 - pass an argument by reference
public void MultiplyBy2(ref int number)
{
number = number * 2;
}
}
static void Main(string[] args)
{
int a = 5;

//this is the argument

Multiplier m = new Multiplier();


//Pass argument a by value
m.MultiplyBy2(a);
Console.WriteLine(a);

//after method is called, a = 5 (a remains UNCHANGED)

//Pass argument a by reference - ref keyword


m.MultiplyBy2(ref a);
Console.WriteLine(a);
//after method is called, a = 10 (a has CHANGED)
Console.ReadLine();
}

METHOD OVERLOADING (COMPILE TIME POLYMORPHISM/EARLY


BINDING)
Method overloading means that you can have many methods with the same name in a class, but the method
signature must be different. i.e. the methods must differ in either the data types of the parameters, and/or the
number of parameters.

E XAMPLE
//Below we have 3 Methods with the same name but different signatures
//Method name is Add
//Accepts 2 parameters of type int
public int Add(int a, int b)
{
return a + b;
}
//Method name is Add
//Accepts 3 parameters of type int
public int Add(int a, int b, int c)
{
return a + b + c;

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

26 |

}
//Method name is Add
//Accepts 2 parameters of type decimal
public decimal Add(decimal a, decimal b)
{
return a + b;
}

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

27 |

5. Inheritance
Inheritance is a relationship between classes whereby one class can get all the functionality (ie. the fields,
properties and methods) of another class, and then extend it. The advantage of inheritance is code re-use: we
inherit from a class instead of re-writing that same functionality in our new class.
The existing class whose functionality we want to use is called the base class (or parent class or super class).
The new class that we create that inherits from the parent class is called the derived class (or child class or sub
class).
The base class is the general class. The derived class is the more specific or specialized class.
Inheritance implements an is a relationship between classes. eg. A customer (derived class) is a person (base
class).

E XAMPLE
//Customer class inherits/derives from Person.
//i.e. Person is the base class
//Customer is the derived class
//Customer acquires all the properties and methods of the Person class.
public class Customer : Person
{
}

Now we can add additional properties and methods to our Customer class.

//Customer class inherits/derives from Person.


//Person is the base class
//Customer is the derived class
//Customer acquires all the properties and methods
//Customer has a FirstName property (from the base
//Customer has a GetFullName method (from the base
//Customer has a CustomerNumber property (from the
//Customer has a GetTransactionAmount method (from
public class Customer : Person
{
private string _customerNumber = "";
private decimal _balance = 0.0M;

of the Person class.


class)
class)
derived class)
the derived class)

public string CustomerNumber


{
get
{
return _customerNumber;

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

28 |

}
}
public decimal Balance
{
get
{
return _balance;
}
set
{
_balance = value;
}
}
public Customer()
{
Console.WriteLine("Customer is instantiated");
}
public string CreateCustomer()
{
_customerNumber = "1000";
return _customerNumber;
}
public decimal GetTransactionAmount(string transactionNumber)
{
//Do a search, find the value and return it
return 100.00M;
}
}

Customer can do everything that Person can do plus additional Customer functionality.
The disadvantage of inheritance is that if the base class changes, the derived class will be affected. In our
previous example, the base class had a method GetFullName. If this method changes in any way (it returns a
different message, or it accepts different parameters, or returns a different data type), it will affect the derived
class.

Multiple Inheritance
C# does not allow multiple inheritance. This means that a derived class cannot have many base classes. A
derived class can only have one base class.

METHOD OVERRIDING (RUN TIME POLYMORPHISM/LATE BINDING)


Before method overriding can occur, the following scenario has to be present:

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

29 |

There is a base class and a derived class.

The base class and the derived class both have a method with the same signature (but
different implementation).

There is an instance of the base class.

If the base class instance invokes the method of the derived class, then the base class method is ignored and
the derived class method is executed. This is called method overriding.
The syntax for method overriding is:
In the base class:
<access specifier> virtual/abstract/override <method name> (<optional parameters>)
{
}

In the derived class


<access specifier> override <method name> (<optional parameters>)
{
}

E XAMPLE
//The base class
public class Vehicle
{
//This method CAN be overridden because of the virtual keyword
public virtual void Describe()
{
Console.WriteLine("A vehicle is used to transport people or goods.");
}
}
//The derived class
public class Car : Vehicle
{
//This method OVERRIDES the base class method.
public override void Describe()
{
Console.WriteLine("A car has four wheels and an engine.");
}
}
class Program
{
static void Main(string[] args)
{
//Create an instance of the base class
Vehicle v = new Vehicle();

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

30 |

//Create an instance of the derived class


Car c = new Car();
DescribeTheObject(v);

//Pass an object of the base class type


//Output: A vehicle is used to transport people or goods

DescribeTheObject(c);

//Pass an object of the derived class type


//Output: A car has four wheels and an engine

Console.ReadLine();
}
//This method illustrates the concept of late binding or run time polymorphism
//This method has a parameter of the base class
//This means that we can pass as an argument an object of the BASE class Vehicle,
//or any object that DERIVES from the base class Vehicle
//ie. we can pass a vehicle object, and we can also pass a car object as arguments
public static void DescribeTheObject(Vehicle z)
{
z.Describe();
}
}

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

31 |

6. Composition
Composition is another way of re-using code. With composition we create a class that contains other classes
(instead of inheriting from another class).
Composition implements a has a relationship between classes. eg. a car has an accelerator and also has a
key.

E XAMPLE
public class SteeringWheel
{
public void Turn()
{
Console.WriteLine("Steering wheel is turned");
}
}
public class Accelerator
{
public void Press()
{
Console.WriteLine("Accelerator is pressed");
}
}
public class Brake
{
public void Press()
{
Console.WriteLine("Brake is pressed");
}
}
//The Car class is composed of other classes
public class Car
{
private SteeringWheel _steeringWheel;
private Accelerator _accelerator;
private Brake _brake;

//A Car is composed of a Steering Wheel


//A Car is composed of an Accelerator
//A Car is composed of a Brake

public Car()
{
_steeringWheel = new SteeringWheel();
_accelerator = new Accelerator();
_brake = new Brake();
}
public void TurnWheel()
{
_steeringWheel.Turn();
}

Copyright Stefanos Arapakis 2014

//Car gets its component 'Steering wheel' to turn

www.eurekalearn.net

32 |

public void Accelerate()


{
_accelerator.Press();
}
public void Stop()
{
_brake.Press();
}

//Car gets its component 'Accelerator' to press

//Car gets its component 'Brake' to press

}
class Program
{
static void Main(string[] args)
{
Car bmw = new Car();
//Create an instance of the Car Class.
//The Car class is composed of other classes.
//i.e. the car class is composed of:
//SteeringWheel, Accelerator and Brake
bmw.Accelerate();
bmw.TurnWheel();
bmw.Stop();
Console.ReadLine();
}
}

COMPOSITION VS INHERITANCE
Deciding on whether to use inheritance or composition is a design issue and beyond the scope of this article.
The simple rule when deciding which to use is:
Use inheritance to implement an is-a relationship, where there clearly a hierarchy from a general class to a more
specific class. Eg. An Apple (derived class) is a Fruit (base class)
Use composition to implement a has-a relationship where there is no clear hierarchy between classes, and
where classes might be unrelated but you want to use these classes to created a unique object. Eg. A car is
composed of a steering wheel, and an accelerator and an engine, and tyres.

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

33 |

7. Interfaces
An interface is a contract specifying how a class must be structured. More specifically, an interface states what
properties, methods and events a class must have. An interface does not include any implementation.
An interface makes the rules of what the class must do, and the class determines how it will be done (i.e. the
class provides the implementation).
The syntax to declare an interface is:
public interface <interface name>
{
//Specify the Contract
}

E XAMPLE
//The interface name is IMobilePhone
//It is generally accepted practice to
//prefix the interface name with the letter 'I'
public interface IMobilePhone
{
void DialANumber(string number);
void SendSMS(string number, string sms);
}
//The class Nokia implements the interface IMobilePhone
//The class MUST have a SendSMS method
//The class MUST have a DialNumber method
public class Nokia : IMobilePhone
{
public void DialANumber(string number)
{
//implementation of how to send the SMS
Console.WriteLine("Nokia is dialing number '" + number + "'");
}
public void SendSMS(string number, string message)
{
//implementation of how to dial a number
Console.WriteLine("Nokia sends a message '" + message + "' to number '" + number + "'");
}
}
//Class Samsung also implements IMobilePhone
//Nokia and Samsung have the same methods, but different implementation
public class Samsung : IMobilePhone
{
public void DialANumber(string number)
{
Console.WriteLine("Samsung is dialing number '" + number + "'");

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

34 |

}
public void SendSMS(string number, string message)
{
Console.WriteLine("Samsung sends a message '" + message + "' to number '" + number +
"'");
}
}

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

35 |

8. Abstract Classes
An abstract class is a class that cannot be instantiated. It can only be inherited from and it is up to the derived
class to implement the desired functionality.
The syntax to define an abstract class is:
public abstract class <classname>
{
//Abstract Methods
//Non abstract Methods
}

An abstract class can contain both abstract methods and non abstract methods.

Abstract Methods
These are methods declared with the abstract keyword.
Abstract methods do not include any implementation. Derived classes must implement all abstract methods.
The syntax to define an abstract method is:
public abstract <return type> <method name>(<optional parameters>);
The syntax to implement an abstract method is:
public override <return type> <method name>(<optional parameters>)
{
}

Non abstract methods


These are normal methods (without the abstract keyword) that do contain implementation.

E XAMPLE
//Abstract class
public abstract class Animal
{
//Non abstract method
public void Breath()
{
Console.WriteLine("Breath");
}
//Abstract method
public abstract void MakeASound();

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

36 |

}
public class Dog : Animal
{
//In order to implement the abstract method "MakeASound",
//we need to use the "override" keyword
public override void MakeASound()
{
Console.WriteLine("Bark");
}
}
public class Cat : Animal
{
public override void MakeASound()
{
Console.WriteLine("Meow");
}
}
class Program
{
static void Main(string[] args)
{
Animal a = new Animal(); //Animal is an abstract class
//Cannot create an instance of Animal
//Does not compile
Dog d = new Dog();
d.Breath();
d.MakeASound();

//Create an instance of the derived class: Dog


//The base class method is called
//The dog class (derived class) provides its own
//implementation

Cat c = new Cat();


c.Breath();
c.MakeASound();

//Create an instance of the derived class: Cat


//The base class method is called
//The cat class (derived class) provides its own
//implementation

Console.ReadLine();
}
}

ABSTRACT CLASS VS INTERFACE


Both an interface and an abstract class force all derived classes to implement its fields, methods and events.
An interface does not contain any implementation.
An abstract class can contain implementation.

WHEN TO USE ABSTRACT CLASSES AND INTERFACES

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

37 |

If you need to have a common implementation in all your derived classes, use an abstract class and implement
the methods required in the base class.
If you need to ensure that unrelated classes have the same functionality, use an interface.
Multiple inheritance is not allowed in C#, so you can use interfaces to allow a single class to implement
functionality from many interfaces.

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

38 |

Namespaces
Namespaces are code blocks that help you organize your code and also help prevent name clashes.
The syntax for namespaces is:
namespace <namespace name>
{
//Classes
//Interfaces
//Enums
//Delegates
}

In real world applications you will have many classes in the same project and/or solution. There is the possibility
that some classes might have the same name and/or method names. In order to distinguish which class and
method you actually want to invoke you must either use the fully qualified name or use the using keyword.
It is common to use the company name as part of the namespace.

E XAMPLE
//Example 1 with the fully qualified name
System.Console.WriteLine("hello");
//System - this is the namespace
//Console - this is the class
//WriteLine - this is the method
//************************************************************************
//Example 2 with the "using" keyword
using System;
Console.WriteLine("hello");

Copyright Stefanos Arapakis 2014

//Declared at the top of the file


//We are using the System namespace
//We do not have to type System.

www.eurekalearn.net

39 |

Arrays
An array is a collection of variables (called elements) of the same data type.
Instead of having multiple variables of the same data type and giving each one a different name, we can create
one variable which contains many values. This is called an array.

SINGLE DIMENSIONAL ARRAYS


A single dimensional array has only one dimension. You can think of a single dimensional array as one row with
columns.
Each element in the array can be accessed by its index (or column position) in the array. It is important to note
that array indexes are zero based. This means that the first element in the array is at index 0 (not 1).

The syntax for declaring a single dimensional array is:


<data type>[] <array name>;

E XAMPLE
int[] i;

//Declare an array
//This means that the array i can hold integer values
//At this point in time, we do not know how many variables i can hold

i = new int[5];

//Initialize the size of the array


//i has 5 elements
//At this point in time, these 5 elements do not have values

//Assigning values to an array


//To assign a value to an array, specify the index (or position) in the array
//Array indexes are zero based, so the first element in the array is accessed by index 0
i[0]
i[1]
i[2]
i[3]
i[4]

=
=
=
=
=

10;
20;
30;
40;
50;

Copyright Stefanos Arapakis 2014

//The
//The
//The
//The
//The

first element in the array is at index 0 and has value 10


second element in the array is at index 1 and has value 20;
third element in the array is at index 2 and has value 30;
fourth element in the array is at index 3 and has value 40;
fifth element in the array is at index 4 and has value 50;

www.eurekalearn.net

40 |

//Read values from an array


Console.WriteLine(i[0]);
Console.WriteLine(i[1]);
Console.WriteLine(i[2]);
Console.WriteLine(i[3]);
Console.WriteLine(i[4]);

//Read
//Read
//Read
//Read
//Read

the
the
the
the
the

first
first
first
first
first

element
element
element
element
element

in
in
in
in
in

the
the
the
the
the

array.
array.
array.
array.
array.

The
The
The
The
The

output
output
output
output
output

is
is
is
is
is

10
20
30
40
50

//*********************************************************************************
//Declaring and initializing an array in one line
string[] j = new string[5];
//j is an array of strings and can hold 5 values
//Declaring and initializing and assigning values to an array in one line
int[] k = new int[] { 10, 20, 30, 40, 50 }; //k is an array of integers and holds 5 values:
//10,20,30,40,50
//To determine the length of the array
Console.WriteLine(k.Length);
//Output is 5
//To loop through all the elements in the array:
//This example will loop 5 times because i.Length is 5
//ie. i has 5 elements in its array
for (int x = 0; x < i.Length; x++)
{
Console.WriteLine(i[x]);
//i is the array
//x is the index value.
//ie. when x is 0, then we access the first element at i[0] and the output is 10
//ie. when x is 1, then we access the second element at i[1] and the output is 20
//ie. when x is 2, then we access the third element at i[2] and the output is 30
//ie. when x is 3, then we access the fourth element at i[3] and the output is 40
//ie. when x is 4, then we access the fifth element at i[4] and the output is 50
}

MULTI-DIMENSIONAL ARRAYS
With multi-dimensional arrays we can have more than one dimension.

Two dimensional arrays


You can think of a two dimensional array as a table. A table has many rows and many columns.

0,0

0,1

0,2

0,3

1,0

1,1

1,2

1,3

2,0

2,1

2,2

2,3

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

41 |

The syntax for declaring a two dimensional array is:


<data type>[,] <array name>;

E XAMPLE
//Multidimensional arrays
//2 dimensional arrays
int[,] c;
//Declare a 2 dimensional array
c = new int[3, 2];

//Initialize the size of the array


//This array has 3 rows and 2 columns

//The first row


c[0, 0] = 1;
c[0, 1] = 2;

//Assign the value 1 to row 0, column 0


//Assign the value 2 to row 0, column 1

//The second row


c[1, 0] = 10;
c[1, 1] = 20;

//Assign the value 10 to row 1, column 0


//Assign the value 20 to row 1, column 1

//The third row


c[2, 0] = 100;
c[2, 1] = 200;

//Assign the value 100 to row 2, column 0


//Assign the value 200 to row 2, column 1

//Read values from the


Console.WriteLine(c[0,
Console.WriteLine(c[0,
Console.WriteLine(c[1,
Console.WriteLine(c[1,
Console.WriteLine(c[2,
Console.WriteLine(c[2,

2-dimensional array
0]); //Output is 1
1]); //Output is 2
0]); //Output is 10
1]); //Output is 20
0]); //Output is 100
1]); //Output is 200

//Loop through a 2-dimensional array


int iNumberOfRows = c.GetLength(0);
int iNumberOfCols = c.GetLength(1);
for (int y = 0; y < iNumberOfRows; y++)
{
for (int z = 0; z < iNumberOfCols; z++)
{
Console.WriteLine(c[y, z]);
}
}

//Get the length of dimension 0 (the rows)


//Get the length of dimension 1 (the columns)
//This loops through each row
//This loops through each column
//Access the value at row y and column z

Console.ReadLine();
//Declaring and initializing a two dimensional array in one line
string[,] d = new string[3,5];
//d is an array of strings and has 3 rows and 5 columns

JAGGED ARRAYS

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

42 |

A jagged array is an array-of-arrays, so an int[][] is an array of int[], each of which can be of different lengths and
occupy their own block in memory.

Limitations of Arrays
1. The size of an array is fixed and cannot be changed once it has been set.
2. Arrays can only contain objects of the same data type.

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

43 |

Collections
Collections are specialized classes for data storage and retrieval and are found in the
System.Collections.Generic namespace.
There are various types of collections. Each collection has advantages and disadvantages, and its use depends
on the features you require.

Iterating a collection
All the collections implement the IEnumerable interface. This means that you can iterate through all the
elements in a collection using the foreach statement.
Types of collections:

ARRAYLIST
An ArrayList is a sophisticated version of an array. In an ArrayList, you can add and remove elements from the
list and the array will resize itself automatically - (a normal array has a fixed size which cannot change after it has
been set). Furthermore, an ArrayList provides additional functionality via its methods and properties.

E XAMPLE
using System.Collections;

//Import this namespace at the top of the class

ArrayList li = new ArrayList();


li.Add(10);
li.Add(20);
li.Add(30);
li.Add(40);
li.Add(50);

//Create
//Add an
//Add an
//Add an
//Add an
//Add an

an instance of an arraylist
integer with value 10 to the
integer with value 20 to the
integer with value 30 to the
integer with value 40 to the
integer with value 50 to the

Console.WriteLine(li[0]);
Console.WriteLine(li[1]);
Console.WriteLine(li[2]);
Console.WriteLine(li[3]);
Console.WriteLine(li[4]);

//Output
//Output
//Output
//Output
//Output

the
the
the
the
the

Console.WriteLine(li.Count);

//returns the number of elements in the arraylist

value
value
value
value
value

at
at
at
at
at

index
index
index
index
index

0.
1.
2.
3.
4.

The
The
The
The
The

arraylist
arraylist
arraylist
arraylist
arraylist

value
value
value
value
value

is
is
is
is
is

at
at
at
at
at

index
index
index
index
index

10
20
30
40
50

//Loop through each element of the array using the foreach statement
foreach (int i in li)
{
Console.WriteLine(i);
}
li.RemoveAt(2);

Copyright Stefanos Arapakis 2014

//Removes the element at index 2 (value 30)

www.eurekalearn.net

0
1
2
3
4

44 |

li.Remove(40);
li.Clear();

//Removes the element with the value 40


//This removes all elements from the arraylist

STACK
A stack is a collection that works on the Last In First Out (LIFO) principle. This means that the last element
inserted into the collection is the first element removed from the collection.
Think of a stack as a pile of books. You place one book A on the table. Then place book B on top of book
A. Then place book C on top of book B. If you want to get a book, you first have to get book C, then
book B, then book A.
To insert an element, use the Push method.
To remove an element, use the Pop method

E XAMPLE
using System.Collections;

//Import this namespace at the top of the class

Stack st = new Stack();


st.Push(10);
st.Push(20);
st.Push(30);
st.Push(40);
st.Push(50);

//Create
//Insert
//Insert
//Insert
//Insert
//Insert

foreach (int i in st)


{
Console.WriteLine(i);
//The output is
//50
//40
//30
//20
//10
}

an
an
an
an
an
an

instance of a stack
integer with value 10
integer with value 20
integer with value 30
integer with value 40
integer with value 50

This is the LAST element inserted into the stack

This is the FIRST element inserted into the stack

//We remove an element from the stack


Console.WriteLine("POP: " + st.Pop());

//The element removed has the value 50.

QUEUE
A queue is a collection that works on the First In First Out (FIFO) principle. This means that the first element
inserted into the collection is the first element removed from the collection.
To insert an element, use the Enqueue method.

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

45 |

To remove an element, use the Dequeue method

E XAMPLE
using System.Collections;

//Import this namespace at the top of the class

Queue q = new Queue();


q.Enqueue(10);
q.Enqueue(20);
q.Enqueue(30);
q.Enqueue(40);
q.Enqueue(50);

//Create
//Insert
//Insert
//Insert
//Insert
//Insert

an
an
an
an
an
an

instance of a queue
integer with value 10
integer with value 20
integer with value 30
integer with value 40
integer with value 50

foreach (int i in q)
{
Console.WriteLine(i);
//The output is
//10
//20
//30
//40
//50
}
//We remove an element from the queue
Console.WriteLine("DEQUEUE: " + q.Dequeue());

Copyright Stefanos Arapakis 2014

//The element removed has the value 10

www.eurekalearn.net

46 |

Generics
Generics make it possible to design classes or methods that have parameters, but without specifying the data
type of the parameters. Instead you specify a generic type parameter T. Only when an instance of a class is
created is the actual data type passed to the class or method.
The advantage of generics is that the same class or method can be used with many different data types (without
having to write multiple classes or methods for each data type).
The problem with normal collections such as ArrayList is as follows:

Decreased Performance
When an item is added to the collection such as an ArrayList, it is implicitly converted to a type Object (this is
called boxing). When the item is read from the collection it needs to be explicitly converted back to its initial
data type (this is called unboxing). This boxing and unboxing is slow, and is especially evident in situations
where the collection has many items.

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

47 |

Generic Collections
Generic Collections are found in the System.Collections.Generic namespace.
Generic collections are faster than collections in the System.Collections namespace and should be used
whenever possible.

LIST
A list is a generic collection that can accept any data type.
The syntax for creating a generic list collection is:
List<T> identifier = new List<T>();

T is a generic parameter. This means that it can accept any data type.

E XAMPLE
List<int> li = new List<int>();

//Create an instance of a generic list collection


//We want this list to hold integer values, so
//we pass <int> as argument for the List<T> parameter

li.Add(10);
li.Add(20);
li.Add(30);
li.Add(40);
li.Add(50);

//Add
//Add
//Add
//Add
//Add

an
an
an
an
an

Console.WriteLine(li.Count);

//Output how many elements there are in the list

Console.WriteLine(li[0]);
Console.WriteLine(li[1]);
Console.WriteLine(li[2]);
Console.WriteLine(li[3]);
Console.WriteLine(li[4]);

//Output
//Output
//Output
//Output
//Output

integer
integer
integer
integer
integer

the
the
the
the
the

with
with
with
with
with

value
value
value
value
value

at
at
at
at
at

value
value
value
value
value

index
index
index
index
index

10
20
30
40
50

0.
1.
2.
3.
4.

to
to
to
to
to

The
The
The
The
The

the
the
the
the
the

list
list
list
list
list

value
value
value
value
value

is
is
is
is
is

at
at
at
at
at

index
index
index
index
index

0
1
2
3
4

10
20
30
40
50

//Loop through each element of the list using the foreach keyword
foreach (int i in li)
{
Console.WriteLine(i);
}
li.RemoveAt(2);
li.Remove(40);
li.Clear();

Copyright Stefanos Arapakis 2014

//Removes the element at index 2. ie it removes the value 30


//Removes the element with the value 40
//This removes all elements from the list

www.eurekalearn.net

48 |

DICTIONARY
A dictionary is a generic collection that holds key-value pairs of any data type.
The syntax for creating a generic list dictionary is:
Dictionary<TKey, TValue> identifier = new Dictionary<TKey, TValue>();

TKey is a generic parameter which means it can accept any data type. Pass a unique key for this parameter that
will uniquely identify this element in the collection. eg. a key might be a customer number.
TValue is a generic parameter which means it can accept any data type. Pass a value for this parameter. eg. a
value might be the customer name.

E XAMPLE
//Create an instance of a dictionary
//The key data type is int
//The value data type is string
Dictionary<int, string> d = new Dictionary<int,string>();
d.Add(5,"John");
d.Add(6,"Peter");
d.Add(7,"Jane");
d.Add(8,"Susan");

//Add
//Add
//Add
//Add

a
a
a
a

Console.WriteLine(d[5]);
Console.WriteLine(d[6]);
Console.WriteLine(d[7]);
Console.WriteLine(d[8]);

//Find
//Find
//Find
//Find

key
key
key
key
the
the
the
the

value/value
value/value
value/value
value/value
element
element
element
element

by
by
by
by

pair.
pair.
pair.
pair.

its
its
its
its

key
key
key
key

The
The
The
The

key
key
key
key

(NOT
(NOT
(NOT
(NOT

is
is
is
is

its
its
its
its

5.
6.
7.
8.

The
The
The
The

index).
index).
index).
index).

value
value
value
value

Output
Output
Output
Output

is
is
is
is

"John"
"Peter"
"Jane"
"Susan"

value:
value:
value:
value:

John
Peter
Jane
Susan

//determine the number of elements in the dictionary


Console.WriteLine("The number of elements: " + d.Count);
//Loop through each key/value pair in the dictionary using the foreach keyword
foreach (KeyValuePair<int, string> z in d)
{
Console.WriteLine("{0} {1}", z.Key, z.Value);
//Output:
//5 John
//6 Peter
//7 Jane
//8 Susan
}
//Loop through each key of the dictionary using the foreach keyword
foreach (int i in d.Keys)
{
Console.WriteLine(d[i]);
//Find the element by its key and output its value
//Output:
//John
//Peter
//Jane

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

49 |

//Susan
}
d.Remove(5);
d.Clear();

//Removes the element with the key 5


//This removes all elements from the dictionary

Exception Handling
Exception handling refers to the way a program responds to an unexpected occurrence while the program is
running.
While a program is running, if there is no exception handling and an exception occurs, the program will behave
unexpectedly, or give incorrect results, or even abnormally abort. With exception handling, the exception is caught,
and then appropriate action is taken depending on the type of exception.
We implement exception handling using the try, catch, finally keywords.

E XAMPLE
try
{
//Here we include code that might possibly throw an exception.
//If an exception occurs in the try block,
//the code in the relevant catch block below will execute.
//If no exception occurs in the try block, the catch blocks below will be ignored.
}
catch (ExceptionType1 e)
{
//If the exception is of type ExceptionType1 then this code is executed.
//This exception can also be thrown to the calling procedure.
//eg. Throw e
}
Catch (ExceptionType2 e){
//If the exception is of type ExceptionType2 then this code is executed.
//This exception can also be thrown to the calling procedure.
//eg. Throw e
}
finally
{
//The finally block is optional.
//If there is a finally block included, then the finally block is ALWAYS executed.
//ie. if there is no exception this block is executed.
//if there is an exception this block is executed.
}

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

50 |

Copyright
Stefanos Arapakis
C# Tutorial for beginners
2014, Stefanos Arapakis
ALL RIGHTS RESERVED. This book contains material protected under International and Federal
Copyright Laws and Treaties. Any unauthorized reprint or use of this material is prohibited. No part
of this book may be reproduced or transmitted in any form or by any means, electronic or
mechanical, including photocopying, recording, or by any information storage and retrieval system
without express written permission from the author / publisher.

Copyright Stefanos Arapakis 2014

www.eurekalearn.net

Anda mungkin juga menyukai