FOR BEGINNERS
Learn the fundamentals of the
C# programming language
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
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
www.eurekalearn.net
4|
www.eurekalearn.net
5|
www.eurekalearn.net
6|
Dictionary.....................................................................................................................................................................................................................48
Exception Handling .......................................................................................................................................................................................................49
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.
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 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
bool
DateTime
DECLARING VARIABLES
We declare variables in the following way:
<data type> <identifier> <optional value>
E XAMPLES
int i;
i = 10;
www.eurekalearn.net
9|
int j = 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;
iMonth = 12;
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
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;
decimal d = 100.34M;
int j = Convert.ToInt32(d);
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
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;
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;
//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
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
int q = 15;
int r = 2;
www.eurekalearn.net
13 |
int s = q % r;
Relational Operators
Relational operators compare values to each other and return a Boolean value (i.e. either true or 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
E XAMPLE
int i = 10;
int j = 20;
int k = 30;
www.eurekalearn.net
14 |
if (i == 10)
{
}
//returns true
if (!(i == 10))
{
}
if (i == 15)
{
}
//returns false
if (!(i == 15))
{
}
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 and decrement operators can appear before or after the operand.
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);
www.eurekalearn.net
16 |
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;
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");
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.
<initializer>
<condition>
<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++
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
}
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
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();
E XAMPLE
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.
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();
FIELDS
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
}
}
www.eurekalearn.net
23 |
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.
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
www.eurekalearn.net
25 |
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;
www.eurekalearn.net
26 |
}
//Method name is Add
//Accepts 2 parameters of type decimal
public decimal Add(decimal a, decimal b)
{
return a + b;
}
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.
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.
www.eurekalearn.net
29 |
The base class and the derived class both have a method with the same signature (but
different implementation).
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>)
{
}
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();
www.eurekalearn.net
30 |
DescribeTheObject(c);
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();
}
}
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;
public Car()
{
_steeringWheel = new SteeringWheel();
_accelerator = new Accelerator();
_brake = new Brake();
}
public void TurnWheel()
{
_steeringWheel.Turn();
}
www.eurekalearn.net
32 |
}
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.
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 + "'");
www.eurekalearn.net
34 |
}
public void SendSMS(string number, string message)
{
Console.WriteLine("Samsung sends a message '" + message + "' to number '" + number +
"'");
}
}
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>)
{
}
E XAMPLE
//Abstract class
public abstract class Animal
{
//Non abstract method
public void Breath()
{
Console.WriteLine("Breath");
}
//Abstract method
public abstract void MakeASound();
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();
Console.ReadLine();
}
}
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.
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");
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.
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];
=
=
=
=
=
10;
20;
30;
40;
50;
//The
//The
//The
//The
//The
www.eurekalearn.net
40 |
//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.
0,0
0,1
0,2
0,3
1,0
1,1
1,2
1,3
2,0
2,1
2,2
2,3
www.eurekalearn.net
41 |
E XAMPLE
//Multidimensional arrays
//2 dimensional arrays
int[,] c;
//Declare a 2 dimensional array
c = new int[3, 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
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
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.
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;
//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);
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);
www.eurekalearn.net
0
1
2
3
4
44 |
li.Remove(40);
li.Clear();
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;
//Create
//Insert
//Insert
//Insert
//Insert
//Insert
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
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.
www.eurekalearn.net
45 |
E XAMPLE
using System.Collections;
//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());
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.
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>();
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);
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();
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
www.eurekalearn.net
49 |
//Susan
}
d.Remove(5);
d.Clear();
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.
}
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.
www.eurekalearn.net