Date post: | 01-Jun-2018 |
Category: |
Documents |
Upload: | anonymous-3bazutpc8 |
View: | 217 times |
Download: | 0 times |
of 50
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
1/50
C# TUTORIAL
FOR BEGINNERS
Learn the fundamentals of the
C# programming language
Stefanos Arapakis www.eurekalearn.net
V1.0
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
2/50
2 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
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 atwww.eurekalearn.netand 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
http://www.eurekalearn.net/http://www.eurekalearn.net/http://www.eurekalearn.net/http://www.eurekalearn.net/8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
3/50
3 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
ContentsC# 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
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
4/50
4 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
The ifstatement ...............................................................................................................................................................................................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
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
5/50
5 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
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
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
6/50
6 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
Dictionary.....................................................................................................................................................................................................................48
Exception Handling .......................................................................................................................................................................................................49
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
7/50
7 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
IntroductionSource codeis 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.
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
8/50
8 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
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 commentAll the content in this block is commented
*/
VARIABLES
A variableis 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:
EX MPLES
inti; //int is the data type. i is the identifier(name) of the variable.//Variable i is declared/defined, but it has no value yet
i = 10; //Variable i now has the value 10
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
9/50
9 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
intj = 5; //Variable j is declared and initialized with value 5
strings = "hello";stringt = "john";
decimald = 105.25M;
boolb = true;
DateTimedte = 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 =
EX MPLES
constintiMonth = 10; //This is valid. A const is declared and initialized with a value.
iMonth = 12; //This is INVALID because a const cannot be modified.
constintjYear; //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 changethe 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.
EX MPLES
intx = 10; //x is a 32 bit integer. This means that it can hold a number up to a 2147483647
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
10/50
10 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
longy = x; //y is a 64 bit integer. This means that it can hold bigger numbers than aninteger.
//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
Convertmethod.
EX MPLES
inti = 100;strings = i; //INVALID. i is an int. s is a string.
//Cannot assign an int to a string. It will not compile.
stringt = Convert.ToString(i); //Valid. int is converted to string
decimald = 100.34M;intj = 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:
?
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.
EX MPLE
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
11/50
11 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
inti = 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 ??
EX MPLE
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 belowintk = j ?? 5; //if j is null, then return 5 else return j
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
12/50
12 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
2. OperatorsOperators 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
EX MPLES
inti = 10;intj = 20;intk = i + j; //Addition
//+ is the operator//i is an operand//j is an operand//the value of k is 30
intx = 4;inty = 3;intz = x - y; //Subtraction
//The value of z is 1.
inta = 4;intb = 3;intc = a * b; //Multiplication.
//The value of c is 12
intd = 14;inte = 7;intf = 0;intg = d / e; //Division. The value of g is 2.inth = d / f; //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.
intq = 15;intr = 2;
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
13/50
13 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
ints = 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 //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
EX MPLES
inti = 5;intj = 7;intk = 7;
boolb1 = i < j; //b1 is true;boolb2 = i j; //b6 is false;boolb7 = j > k; //b7 is false;boolb8 = j >= k; //b8 is true;
boolb9 = j == k; //b9 is true;boolb10 = i == k; //b10 is false;boolb11 = j != k; //b11 is false;
boolb12 = i != k; //b12 is true;
Logical Operators
&& //Logical AND If expression A is true and expression B is true, then it returns true|| //Logical OR If expression A is true or expression B is true, then it returns true! //Logical NOT - If the result it true, then it changes the result to false.
If the result is false, then it changes the result to true.
EX MPLE
inti = 10;intj = 20;intk = 30;
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
14/50
14 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
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.
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
15/50
15 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
3.Flow ControlFlow 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 switchstatement.
The ifstatement
The ifstatement 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 ifstatement is as follows:
if(){
//this statement will execute if the above expression is true}elseif()
{//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.}
EX MPLE
Console.WriteLine("Enter your age"); //Ask for input from the userstringsAge = Console.ReadLine(); //Read the user inputintiAge = Convert.ToInt16(sAge); //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 executeConsole.WriteLine("You are old enough to enter");
}elseif(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
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
16/50
16 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
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 switchstatement 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() //the expression must be a string or an integer{
case://this statement will execute if the above constant-expression is truebreak; //this will exit out of the switch statement
default:
//this statement will execute if none of the above constant-expressions are truebreak;
}
EX MPLE
Console.WriteLine("Enter a number from 1 to 3 ?"); //Ask for input from the userstringsInput = Console.ReadLine(); //Read the user inputintiInput = Convert.ToInt16(sInput); //Convert the string to an integer
switch(iInput){
case1:Console.WriteLine("You win a car"); //This line will execute if the user entered 1break;
case2:Console.WriteLine("You win a scooter");//This line will execute if the user entered 2break;
case3:Console.WriteLine("You win a bike"); //This line will execute if the user entered 3
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
17/50
17 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
break;
default:Console.WriteLine("Sorry. You don't win anything"); //This line will execute if the
//user entered any other numberbreak;
}
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(; ; ){
//This code is executed many times}
- specify the start value.
- the loop will occur while the condition is true.
- specify what must be done to the variable initialized after each loop.
EX MPLE
for(inti = 0; i < 10; i++){
Console.WriteLine(i.ToString());
}
//Explanation//int i = 0 - we initialize a variable called i with the value 0.
i.e. our loop starts from 0.//i < 10 - we loop while the condition is true. i.e we loop while i < 10//i++ - after each loop, we increment i by 1.
//So, this loop will run 10 times.//The output will be://0//1//2//3
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
18/50
18 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
//4//5//6//7//8//9
//*********************************************************************************
//To loop through all the elements in the array:int[] i = newint[] { 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 arrayfor(intx = 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(){
//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.
EX MPLE
inti = 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 ii++; //increment i.
}
//Explanation//This loop will execute 10 times.//The output will be//0
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
19/50
19 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
//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.
EX MPLE
//Dontworry if you dont understand all the code below.//Just understand the concept://We loop while we are not at the end of the filestringsFileName = "C:\file1.csv";FileInfofileIn = newFileInfo(sFileName);
StreamReaderreader = 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 whileloop can execute zero or more times.
A do whileloop can execute one or more times. i.e. a do whileloop 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()
EX MPLE
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
20/50
20 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
inti = 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.
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
21/50
21 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
4. ClassesClasses 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 classis a blueprintor template. i.e. it contains info of howan object should be built.
An objectis 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:
class{
//Fields//Properties//Methods//Events
}
EX MPLE
publicclassPerson{
}
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:
= new ();
EX MPLE
Personjohn = newPerson();
A class contains members called fields,propertiesand methods.
FIELDS
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
22/50
22 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
A field is a variable that is declared directly in a class. It is generally accepted best practice to declare fields with
theprivateaccess 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:
EX MPLE
privatestring_firstName = "";
PROPERTIES
A property is an attribute of the class and is accessible by external code as well as internally within the class. It isused 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:
{
get{
return }set
{ = value;
}}
EX MPLE
privatestring_firstName = ""; //This is the private field: accessible internally only
//This is the property: accessible externally and internallypublicstringFirstName{
get{
return_firstName; //read the value from the field}set{
_firstName = value; //save the value to the field}
}
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
23/50
23 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
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:
(){
//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.
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
24/50
24 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
EX MPLE
//Public - accessible internally and externally//Method Name: GetFullName//No parameters
//Returns a stringpublicstringGetFullName(){
return_firstName + " "+ _lastName;}
//Public - accessible internally and externally//Method Name: GetAge//Accepts 1 parameter of data type: DateTime.//Returns a TimeSpanpublicTimeSpanGetAge(DateTimedateOfBirth){
returnDateTime.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 cannotchange the value of the argument
outside of the method.
By Reference
Arguments are only passed by reference in C# if you use the refor outkeyword.
When an argument is passed by reference to a method using the refkeyword, the method canchange the
value of the argument outside of the method.
When a method is passed by reference to a method using the outkeyword, the method mustchange the value
of the argument outside of the method.
EX MPLE
publicclassMultiplier{
//Method 1 - pass an argument by value
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
25/50
25 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
publicvoidMultiplyBy2(intnumber){
number = number * 2;}
//Method 2 - pass an argument by referencepublicvoidMultiplyBy2(refintnumber){
number = number * 2;}
}
staticvoidMain(string[] args){
inta = 5; //this is the argument
Multiplierm = newMultiplier();
//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 keywordm.MultiplyBy2(refa);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
X MPLE
//Below we have 3 Methods with the same name but different signatures
//Method name is Add//Accepts 2 parameters of type int
publicintAdd(inta, intb){returna + b;
}
//Method name is Add//Accepts 3 parameters of type intpublicintAdd(inta, intb, intc){
returna + b + c;
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
26/50
26 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
}
//Method name is Add//Accepts 2 parameters of type decimalpublicdecimalAdd(decimala, decimalb){
returna + b;}
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
27/50
27 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
5. InheritanceInheritance 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 generalclass. The derived class is the more specificor specializedclass.
Inheritance implements an is a relationship between classes.eg. A customer (derived class) is aperson (base
class).
EX MPLE
//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.publicclassCustomer: 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 of the Person class.//Customer has a FirstName property (from the base class)//Customer has a GetFullName method (from the base class)//Customer has a CustomerNumber property (from the derived class)//Customer has a GetTransactionAmount method (from the derived class)
publicclassCustomer: Person{
privatestring_customerNumber = "";privatedecimal_balance = 0.0M;
publicstringCustomerNumber{
get{
return_customerNumber;
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
28/50
28 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
}}
publicdecimalBalance{
get{
return_balance;}set{
_balance = value;}
}
publicCustomer(){
Console.WriteLine("Customer is instantiated");}
publicstringCreateCustomer(){
_customerNumber = "1000";
return_customerNumber;}
publicdecimalGetTransactionAmount(stringtransactionNumber){
//Do a search, find the value and return itreturn100.00M;
}}
Customer can do everything that Person can do plusadditional 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:
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
29/50
29 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
There is a base class and a derived class.
The base class and the derived class both have a method with the s me sign ture (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:
virtual/abstract/override (){}
In the derived class
override (){}
EX MPLE
//The base classpublicclassVehicle{
//This method CAN be overridden because of the virtual keywordpublicvirtualvoidDescribe()
{Console.WriteLine("A vehicle is used to transport people or goods.");
}}
//The derived classpublicclassCar: Vehicle{
//This method OVERRIDES the base class method.publicoverride voidDescribe(){
Console.WriteLine("A car has four wheels and an engine.");}
}
classProgram{
staticvoidMain(string[] args){
//Create an instance of the base classVehiclev = newVehicle();
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
30/50
30 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
//Create an instance of the derived classCarc = newCar();
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 argumentspublicstaticvoidDescribeTheObject(Vehiclez){
z.Describe();}}
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
31/50
31 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
6. CompositionComposition is another way of re-using code. With composition we create a class that containsother classes
(instead of inheriting from another class).
Composition implements a has a relationship between classes.eg. a car has anaccelerator and also has a
key.
EX MPLE
publicclassSteeringWheel{
publicvoidTurn(){
Console.WriteLine("Steering wheel is turned");
}}
publicclassAccelerator{
publicvoidPress(){
Console.WriteLine("Accelerator is pressed");}
}
publicclassBrake{
publicvoidPress()
{Console.WriteLine("Brake is pressed");
}}
//The Car class is composed of other classespublicclassCar{
privateSteeringWheel_steeringWheel; //A Car is composed of a Steering WheelprivateAccelerator_accelerator; //A Car is composed of an AcceleratorprivateBrake_brake; //A Car is composed of a Brake
publicCar()
{ _steeringWheel = newSteeringWheel();_accelerator = newAccelerator();_brake = newBrake();
}
publicvoidTurnWheel(){
_steeringWheel.Turn(); //Car gets its component 'Steering wheel' to turn}
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
32/50
32 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
publicvoidAccelerate(){
_accelerator.Press(); //Car gets its component 'Accelerator' to press}
publicvoidStop(){
_brake.Press(); //Car gets its component 'Brake' to press}
}
classProgram{
staticvoidMain(string[] args){
Carbmw = newCar(); //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-arelationship, 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-arelationship 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.
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
33/50
33 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
7. InterfacesAn interfaceis a contract specifying how a class mustbe structured. More specifically, an interface states what
properties, methods and events a class must have. An interface does notinclude 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:
publicinterface{
//Specify the Contract}
EX MPLE
//The interface name is IMobilePhone//It is generally accepted practice to//prefix the interface name with the letter 'I'publicinterfaceIMobilePhone{
voidDialANumber(stringnumber);voidSendSMS(stringnumber, stringsms);
}
//The class Nokia implements the interface IMobilePhone//The class MUST have a SendSMS method
//The class MUST have a DialNumber methodpublicclassNokia: IMobilePhone{
publicvoidDialANumber(stringnumber){
//implementation of how to send the SMSConsole.WriteLine("Nokia is dialing number '"+ number + "'");
}
publicvoidSendSMS(stringnumber, stringmessage){
//implementation of how to dial a numberConsole.WriteLine("Nokia sends a message '"+ message + "' to number '"+ number + "'");
}}
//Class Samsung also implements IMobilePhone//Nokia and Samsung have the same methods, but different implementationpublicclassSamsung: IMobilePhone{
publicvoidDialANumber(stringnumber){
Console.WriteLine("Samsung is dialing number '"+ number + "'");
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
34/50
34 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
}
publicvoidSendSMS(stringnumber, stringmessage){
Console.WriteLine("Samsung sends a message '"+ message + "' to number '"+ number +"'");
}}
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
35/50
35 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
8. Abstract ClassesAn 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:
publicabstractclass{
//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 notinclude any implementation. Derived classes mustimplement all abstract methods.
The syntax to define an abstract method is:
publicabstract ();
The syntax to implement an abstract method is:
publicoverride (){
}
Non abstract methods
These are normal methods (without the abstract keyword) that do contain implementation.
E
X MPLE
//Abstract class
publicabstractclassAnimal{
//Non abstract methodpublicvoidBreath(){
Console.WriteLine("Breath");}
//Abstract methodpublicabstractvoidMakeASound();
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
36/50
36 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
}
publicclassDog: Animal{
//In order to implement the abstract method "MakeASound",//we need to use the "override" keywordpublicoverridevoidMakeASound(){
Console.WriteLine("Bark");}
}
publicclassCat: Animal{
publicoverridevoidMakeASound(){
Console.WriteLine("Meow");}
}
classProgram{
staticvoidMain(string[] args){
Animala = newAnimal(); //Animal is an abstract class//Cannot create an instance of Animal//Does not compile
Dogd = newDog(); //Create an instance of the derived class: Dogd.Breath(); //The base class method is calledd.MakeASound(); //The dog class (derived class) provides its own
//implementation
Catc = newCat(); //Create an instance of the derived class: Catc.Breath(); //The base class method is calledc.MakeASound(); //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 notcontain any implementation.
An abstract class cancontain implementation.
WHEN TO USE ABSTRACT CLASSES AND INTERFACES
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
37/50
37 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
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.
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
38/50
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
39/50
39 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
ArraysAn arrayis 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).
0 1 2 3 4
The syntax for declaring a single dimensional array is:
[] ;
EX MPLE
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 = newint[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] = 10; //The first element in the array is at index 0 and has value 10i[1] = 20; //The second element in the array is at index 1 and has value 20;i[2] = 30; //The third element in the array is at index 2 and has value 30;i[3] = 40; //The fourth element in the array is at index 3 and has value 40;i[4] = 50; //The fifth element in the array is at index 4 and has value 50;
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
40/50
40 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
//Read values from an arrayConsole.WriteLine(i[0]); //Read the first element in the array. The output is 10Console.WriteLine(i[1]); //Read the first element in the array. The output is 20Console.WriteLine(i[2]); //Read the first element in the array. The output is 30Console.WriteLine(i[3]); //Read the first element in the array. The output is 40Console.WriteLine(i[4]); //Read the first element in the array. The output is 50
//*********************************************************************************
//Declaring and initializing an array in one linestring[] j = newstring[5]; //j is an array of strings and can hold 5 values
//Declaring and initializing and assigning values to an array in one lineint[] k = newint[] { 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 arrayConsole.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 arrayfor(intx = 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
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
41/50
41 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
The syntax for declaring a two dimensional array is:
[,] ;
EX MPLE
//Multidimensional arrays//2 dimensional arraysint[,] c; //Declare a 2 dimensional array
c = newint[3, 2]; //Initialize the size of the array//This array has 3 rows and 2 columns
//The first rowc[0, 0] = 1; //Assign the value 1 to row 0, column 0c[0, 1] = 2; //Assign the value 2 to row 0, column 1
//The second row
c[1, 0] = 10; //Assign the value 10 to row 1, column 0c[1, 1] = 20; //Assign the value 20 to row 1, column 1
//The third rowc[2, 0] = 100; //Assign the value 100 to row 2, column 0c[2, 1] = 200; //Assign the value 200 to row 2, column 1
//Read values from the 2-dimensional arrayConsole.WriteLine(c[0, 0]); //Output is 1Console.WriteLine(c[0, 1]); //Output is 2Console.WriteLine(c[1, 0]); //Output is 10Console.WriteLine(c[1, 1]); //Output is 20Console.WriteLine(c[2, 0]); //Output is 100Console.WriteLine(c[2, 1]); //Output is 200
//Loop through a 2-dimensional arrayintiNumberOfRows = c.GetLength(0); //Get the length of dimension 0 (the rows)intiNumberOfCols = c.GetLength(1); //Get the length of dimension 1 (the columns)
for(inty = 0; y < iNumberOfRows; y++) //This loops through each row{
for(intz = 0; z < iNumberOfCols; z++) //This loops through each column{
Console.WriteLine(c[y, z]); //Access the value at row y and column z}
}
Console.ReadLine();
//Declaring and initializing a two dimensional array in one linestring[,] d = newstring[3,5]; //d is an array of strings and has 3 rows and 5 columns
JAGGED ARRAYS
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
42/50
42 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
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.
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
43/50
43 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
CollectionsCollectionsare 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 IEnumerableinterface. This means that you can iterate through all the
elements in a collection using the foreachstatement.
Types of collections:
ARRAYLIST
An ArrayListis 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
X MPLE
usingSystem.Collections; //Import this namespace at the top of the class
ArrayListli = newArrayList(); //Create an instance of an arraylistli.Add(10); //Add an integer with value 10 to the arraylist at index 0li.Add(20); //Add an integer with value 20 to the arraylist at index 1li.Add(30); //Add an integer with value 30 to the arraylist at index 2li.Add(40); //Add an integer with value 40 to the arraylist at index 3li.Add(50); //Add an integer with value 50 to the arraylist at index 4
Console.WriteLine(li[0]); //Output the value at index 0. The value is 10Console.WriteLine(li[1]); //Output the value at index 1. The value is 20Console.WriteLine(li[2]); //Output the value at index 2. The value is 30Console.WriteLine(li[3]); //Output the value at index 3. The value is 40Console.WriteLine(li[4]); //Output the value at index 4. The value is 50
Console.WriteLine(li.Count); //returns the number of elements in the arraylist
//Loop through each element of the array using the foreach statementforeach(inti inli){
Console.WriteLine(i);}
li.RemoveAt(2); //Removes the element at index 2 (value 30)
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
44/50
44 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
li.Remove(40); //Removes the element with the value 40li.Clear(); //This removes all elements from the arraylist
STACK
A stackis 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. Ifyou want to get a book, you first have to get book C, then
book B, then book A.
To insert an element, use the Pushmethod.
To remove an element, use the Popmethod
EX MPLE
usingSystem.Collections; //Import this namespace at the top of the class
Stackst = newStack(); //Create an instance of a stackst.Push(10); //Insert an integer with value 10st.Push(20); //Insert an integer with value 20st.Push(30); //Insert an integer with value 30st.Push(40); //Insert an integer with value 40st.Push(50); //Insert an integer with value 50
foreach(inti inst){Console.WriteLine(i);//The output is//50 This is the LAST element inserted into the stack//40//30//20//10 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 queueis 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 Enqueuemethod.
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
45/50
45 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
To remove an element, use the Dequeuemethod
EX MPLE
usingSystem.Collections; //Import this namespace at the top of the class
Queueq = newQueue(); //Create an instance of a queueq.Enqueue(10); //Insert an integer with value 10q.Enqueue(20); //Insert an integer with value 20q.Enqueue(30); //Insert an integer with value 30q.Enqueue(40); //Insert an integer with value 40q.Enqueue(50); //Insert an integer with value 50
foreach(inti inq){
Console.WriteLine(i);//The output is//10//20//30//40//50
}
//We remove an element from the queueConsole.WriteLine("DEQUEUE: "+ q.Dequeue()); //The element removed has the value 10
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
46/50
46 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
GenericsGenericsmake 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 iscalled 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.
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
47/50
47 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
Generic CollectionsGeneric 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 listis a generic collection that can accept any data type.
The syntax for creating a generic list collection is:
List identifier = newList();
Tis a generic parameter. This means that it can accept any data type.
EX MPLE
List li = newList(); //Create an instance of a generic list collection//We want this list to hold integer values, so//we pass as argument for the List parameter
li.Add(10); //Add an integer with value 10 to the list at index 0li.Add(20); //Add an integer with value 20 to the list at index 1li.Add(30); //Add an integer with value 30 to the list at index 2
li.Add(40); //Add an integer with value 40 to the list at index 3li.Add(50); //Add an integer with value 50 to the list at index 4
Console.WriteLine(li.Count); //Output how many elements there are in the list
Console.WriteLine(li[0]); //Output the value at index 0. The value is 10Console.WriteLine(li[1]); //Output the value at index 1. The value is 20Console.WriteLine(li[2]); //Output the value at index 2. The value is 30Console.WriteLine(li[3]); //Output the value at index 3. The value is 40Console.WriteLine(li[4]); //Output the value at index 4. The value is 50
//Loop through each element of the list using the foreach keywordforeach(inti inli){
Console.WriteLine(i);}
li.RemoveAt(2); //Removes the element at index 2. ie it removes the value 30li.Remove(40); //Removes the element with the value 40li.Clear(); //This removes all elements from the list
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
48/50
48 |
Copyright Stefanos Arapakis 2014 www.eurekalearn.net
DICTIONARY
A dictionaryis a generic collection that holds key-value pairs of any data type.
The syntax for creating a generic list dictionary is:
Dictionary identifier = newDictionary();
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.
EX MPLE
//Create an instance of a dictionary//The key data type is int//The value data type is stringDictionary d = newDictionary();
d.Add(5,"John"); //Add a key value/value pair. The key is 5. The value is "John"d.Add(6,"Peter"); //Add a key value/value pair. The key is 6. The value is "Peter"d.Add(7,"Jane"); //Add a key value/value pair. The key is 7. The value is "Jane"d.Add(8,"Susan"); //Add a key value/value pair. The key is 8. The value is "Susan"
Console.WriteLine(d[5]); //Find the element by its key (NOT its index). Output value: JohnConsole.WriteLine(d[6]); //Find the element by its key (NOT its index). Output value: PeterConsole.WriteLine(d[7]); //Find the element by its key (NOT its index). Output value: JaneConsole.WriteLine(d[8]); //Find the element by its key (NOT its index). Output value: Susan
//determine the number of elements in the dictionaryConsole.WriteLine("The number of elements: "+ d.Count);
//Loop through each key/value pair in the dictionary using the foreach keywordforeach(KeyValuePair z ind){
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 keywordforeach(inti ind.Keys){
Console.WriteLine(d[i]); //Find the element by its key and output its value//Output://John//Peter//Jane
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
49/50
8/9/2019 CSharpTutorialForBeginners-StefanosArapakis
50/50
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.