0% found this document useful (0 votes)
15 views

2 Programming With C#-I

This document provides an overview of C# fundamentals including data types, variables, constants, and strings. It discusses the different data types in C# like integer, floating point, boolean, character and string types. It also covers variable declaration and initialization, constant variables, the object type, literals, and string literals. The document aims to help students understand C# language fundamentals and write basic C# programs.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

2 Programming With C#-I

This document provides an overview of C# fundamentals including data types, variables, constants, and strings. It discusses the different data types in C# like integer, floating point, boolean, character and string types. It also covers variable declaration and initialization, constant variables, the object type, literals, and string literals. The document aims to help students understand C# language fundamentals and write basic C# programs.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 175

Chapter Three

C# fundamentals

11/12/2023 1
Objectives
 After the end this lesson the student will be able to
 Understand C# language fundamentals
> Data type, variables and constants, …
 Write a C# program statement
 Debug C# program in VS
 Develop OO program with C#

11/12/2023 2
Lesson Outline
 C# fundamentals
 Data types, variables and constants
 Comments in C#
 Namespace
 Type casting
 Data type conversion
 Operators and Expressions
 Console Input / Output
 C# Code control structure
 Conditional statements
 Looping statements
 Jump statements
11/12/2023 3
C#(C-Sharp)
 Microsoft C# (pronounced See Sharp) developed by
Microsoft Corporation, USA
 New programming language that runs on the .NET
Framework
 C# is simple, modern, type safe, and object oriented
 Combines the best features of Visual Basic, C++ and Java

11/12/2023 4
C# Features
 Simple
 Modern
 Object-Oriented
 Type-safe
 Versionable
 Compatible
 Secure

11/12/2023 5
Data Types
 Are sets (ranges) of values that have similar
characteristics
 Data types are characterized by:
 Name – for example, int;
 Size (how much memory they use) – for example, 4 bytes;
 Default value – for example 0.
 two major sets of data types in C#
 value types
> store their own data
 reference types
> Store a reference to the area of memory where the data is stored

11/12/2023 6
Data Types …
 Basic data types in C# :
 Integer types – sbyte, byte, short, ushort, int, uint, long, ulong;
 Real floating-point types – float, double;
 Real type with decimal precision – decimal;
 Boolean type – bool;
 Character type – char;
 String – string;
 Object type – object.
 These data types are called primitive (built-in types),
 because they are embedded in C# language at the lowest level.

11/12/2023 7
Data Types …
 C# Keyword Bytes .Net Type default Min value Max value
 sbyte 1 SByte 0 -128 127
 byte 1 Byte 0 0 255
 short 2 Int160 -32768 32767
 ushort 2 UInt16 0 0 65535
 int 4 Int320 -2147483648 2147483647
 uint 4 UInt32 0u 0 4294967295
 long 8 Int640L -9223372036854775808 9223372036854775807
 ulong 8 UInt64 0u 0 18446744073709551615
 float 4 Single 0.0f ±1.5×10 -45 ±3.4×1038
 double 8 Double 0.0d ±5.0×10 -324 ±1.7×10308
 decimal 16 Decimal 0.0m ±1.0×10-28 ±7.9×1028
 bool 1 Boolean false Two possible values: true and false
 char 2 Char'\u0000' '\u0000' '\uffff‘
 object - Object null - a reference to a String object
 string - String null - a reference to any type of object
11/12/2023 8
C# > Variables
A named area of memory

11/12/2023 9
Variables
 a named area of memory
 stores a value from a particular data type, and
 is accessible in the program by its name.
 Stores a value that can change as the program executes
 Before use it must be declared
 Variable declaration contains
 Data types
 Name
 Initial value
 Valid C# variable name
 Start with A-Z or a-z or _
 Can include number and _
 cannot coincide with a keyword
> Use "@". For example, @char and @null
 C# is case sensitive
 E.g. salary, number1, total_mark
 Naming convention
 camelNotation
> E,g. letterGrade
 PascalNotation
> E.g. LetterGrade
11/12/2023 10
Variables > keywords
 Reserved words by the language for some purpose
 Can’t be used by programmer for other purpose except they are reserved for
abstract as base bool break byte
case catch char checked class const
continue decimal default delegate do double
else enum event explicit extern false
finally fixed float for foreach goto
if implicit in int interface internal
is lock long namespace new null
object operator out override params private
protected public readonly ref return sbyte
sealed short sizeof stackalloc static string
struct switch this throw true try
typeof uint ulong unchecked unsafe ushort
using virtual void volatile while …
11/12/2023 11
Variables > Declaration
 Variable declaration and initialization
Syntax
type variableName;
variableName=value;
 Several ways of initializing:
 By using the new keyword
 By using a literal expression
 By referring to an already initialized variable

11/12/2023 12
Variables > Example
 Example
int num = new int(); // num = 0
int x; //declaration statement
x=0; //assignment statement
char grade=‘A’; //enclose a character value in single quotes
double price = 10.55; //declare and initialize a value with 1 stmt
double scientificNumber= 3.45e+6; //scientific notation
decimal salary = 12345.67m; //m or M indicates a decimal value,
monetary(money)
float interestRate = 5.25f; //f or F indicates a float value
bool isValid = false; //declare and initialize a value with 1 stmt
double scgpa = 3.2, cgpa=3.12; //initialize 2 variables with 1 stmt
string greeting = "Hello World!"; //enclose a string value in double quotes
11/12/2023 13
Variables > Constant variables
 Constant
 Stores a value that can’t be changed as the program executes
 Always declared and initialized in a single statement
 Declaration statement begins with const keyword
 Capitalize the first letter in each word of a constant also common
practice – PascalNotation
 Example
const double Pension = 0.06;
const int DaysInWeek = 7;
const int Km = 100;

11/12/2023 14
Variables > String data type
 Strings are sequences of characters.
 declared by the keyword string
 enclosed in double quotation marks
 default value is null
 Example
string firstName = “Abebe”;
string lastName = “Kebede”;
string fullName = firstName + “ “ + lastName;
 Various text-processing operations can be performed using strings:
 concatenation (joining one string with another),
 splitting by a given separator,
 searching,
 replacement of characters and others.
 + concatenate, += append, More in working with Date and String class
11/12/2023 15
Variables > Object Type
 Object type is a special type
 which is the parent of all other types in the .NET Framework
 Declared with the keyword object,
 it can take values from any other type.
 It is a reference type,
> i.e. an index (address) of a memory area which stores the actual value.
 Example
object object1 = 1;
object object2 = “Two";

11/12/2023 16
Variables > Literals
 Primitive types, which we already met, are special data
types built into the C# language.
 Their values specified in the source code of the program are
called literals.
 types of literals:
 Boolean e.g bool open = true;
 Integer
 Real
 Character
 String
 Object literal null
11/12/2023 17
Variables > Literals > Escaping Sequences
 the most frequently used escaping sequences:
 \' – single quote
 \" – double quotes
 \\ – backslash
 \n – new line
 \t – offset (tab)
 \uXXXX – char specified by its Unicode number, for example \u1200.
 Example
 char symbol = 'a'; // An ordinary symbol
 symbol = '\u1200'; // Unicode symbol code in a hexadecimal format
 symbol = '\u1201'; // ሁ (” Hu” Amharic Letter )
 symbol = '\t'; // Assigning TAB symbol
 symbol = '\n'; // Assigning new line symbol
11/12/2023 18
Variables > String Literals
 Strings can be preceded by the @ character that
specifies a quoted string (verbatim string)
 string quotation = "\"Hello, C#\", he said.";
 string path = "C:\\Windows\\Notepad.exe";
 string verbatim = @"The \ is not escaped as \\.
I am at a new line.";

11/12/2023 19
Variables > Scope
 scope
 Visibility/accessibility of a variable
 determines what codes has access to it
 Code block scope
 method scope
 class scope
 Access Modifier / Accessibility/life time extender
 Private – only in the same class
 Internal – in the same assembly
 Protected – same class or subclass (inherited class)
 public – by any object in anywhere
11/12/2023 20
Type Casting
 Casting – converting one data from one data type to another
 Two type casting
 Implicit casting
> Performed automatically
> Widening conversion
 Used to convert data with a less precise type to a more precise type
> byte-> short -> int -> long->decimal
> E.g.
 double mark =85;
 int grade =‘A’
 Explicit casting
> Narrowing conversion
 Casts data from a more precise data type to a less precise data type
> (type) expression
> E.g
 int mark = (int)85.25;
11/12/2023 21
Convert data type
 .Net framework provides structures and classes that defines data type
 Structure defines a value type
 Class defines a reference type
 Structure
 Byte – byte – an 8-bit unsigned integer
 Int16 – short - a 16-bit signed integer
 Int32 – int – A 32-bit signed integer
 Int64 – long – A 64-bit signed integer
 Single – float – a single-precision floating number
 Double – double - a double precision floating number
 Decimal – decimal – a 96-bit decimal value
 Boolean – bool – a true or false value
 Char – char - a single character
 Class
 String – string – a reference to a String object
 Object – object – a reference to any type of object
11/12/2023 22
Convert data type …
 Methods used to convert data types
 ToString
> Converts the value to its equivalent string representation using the specified format, if any
> ToString([format])
 Parse
> A static method that converts the specified string to an equivalent data value
> If the string can’t converted, an exception occurred
> Parse(string)
 TryParse
> A static method that converts the specified string to an equivalent data value and
> Stores it in the result variable
> Returns a true value if the string is converted, otherwise, returns a false value
> If the string can’t converted, an exception occurred
 Static methods of Convert class
> ToDecima(value) – converts the value to the decimal data type
> ToDouble(value) - converts the value to the double data type
> ToInt32(value) – converts the value to the int data type
> …
11/12/2023 23
Exercise 1
 declare and initialize the following types of data
 int
 float
 double
 string
 decimal

you must use appropriate naming convention.

11/12/2023 24
Comments in C#
 To include information about your code
 Not readable by the compiler
 Single line comment
//comment
 Multiple line comment
/* --------------
---- multiline comment -------
--------------*/

11/12/2023 25
Exercise
1. Which of the ff is a valid C# variable name?
A. new
B. 1stYear
C. grade
D. father-name
2. Declare a variable that stores
a. letter grade of a subject
b. CGPA of a student
c. Balance of a customer
3. Assign an initial value for the above variables
a. To their domain default
b. Using new key word
4. Write the output of the ff code snippet
string exercise = @“Please Students \ answer this exercise \\.
Please participate actively.";
Console.WriteLine(exercise );
5. Give an example for implicit and explicit type casting.
11/12/2023 26
C# > Operators and Expressions
Performing Simple Calculations with C#

11/12/2023 27
Operators and Expressions
 Operator
 is an operation performed over data at runtime
 Takes one or more arguments (operands)
 Produces a new value
 Operators have precedence
 Precedence defines which will be evaluated first
 Expressions
 are sequences of operators and operands that are evaluated to a
single value

11/12/2023 28
Operators in C#
 Operators in C# :
 Unary – take one operand
 Binary – take two operands
 Ternary – takes three operands
 Except for the assignment operators, all binary operators
are left-associative
 The assignment operators and the conditional operator (?:)
and ?? are right-associative

11/12/2023 29
Operators in C# > Categories of Operators
Category Operators
Arithmetic +, -, *, /, %, ++, --
Logical &&, ||, ^, !,
Binary/Bitwise &, |, ^, ~, <<, >>
Comparison/
==, !=, < >, <=, >=
Relationa
=, +=, -=, *=, /=, %=, &=, |
Assignment
=, ^=, <<=, >>=
String concatenation +
Type conversion is, as, typeof
Other ., [], (), ?:, ??, new
11/12/2023 30
Operators in C# > Operators Precedence
Precedence Operators
Highest ++ -- (postfix) new typeof
++ -- (prefix) + - (unary) ! ~
*/%
+-
<< >>
< > <= >= is as
== !=
&
Lower ^
11/12/2023 31
Operators in C# > Operators Precedence
Precedence Operators
Higher |
&&
||
?:, ??
=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |
Lowest =
 Parenthesis is operator always has highest precedence
 Note: prefer using parentheses, even when it seems difficult
to do so
11/12/2023 32
Arithmetic Operators
 Arithmetic operators +, -, * are the same as in math
 Division operator / if used on integers returns integer
(without rounding) or exception
 Division operator / if used on real numbers returns real
number or Infinity or NaN
 Remainder operator % returns the remainder from division
of integers
 The special addition operator ++ increments a variable
 The special subtraction operator -- decrements a variable

11/12/2023 33
Arithmetic Operators > Example
 int squarePerimeter = 17;
 double squareSide = squarePerimeter/4.0;
 double squareArea = squareSide*squareSide;
 Console.WriteLine(squareSide); // 4.25
 Console.WriteLine(squareArea); // 18.0625

 int a = 5;
 int b = 4;
 Console.WriteLine( a + b ); // 9
 Console.WriteLine( a + b++ ); // 9
 Console.WriteLine( a + b ); // 10
 Console.WriteLine( a + (++b) ); // 11
 Console.WriteLine( a + b ); // 11

 Console.WriteLine(11 / 3); // 3
 Console.WriteLine(11 % 3); // 2
 Console.WriteLine(12 / 3); // 4
11/12/2023 34
Logical Operator
 Logical operators take boolean operands and return
boolean result
 Operator ! (logical Negation) turns true to false and false to
true
 Behavior of the operators &&(AND), ||(OR) and ^
(exclusive OR)
Operation || || || || && && && && ^ ^ ^ ^
Operand1 0 0 1 1 0 0 1 1 0 0 1 1
Operand2 0 1 0 1 0 1 0 1 0 1 0 1
Result 0 1 1 1 0 0 0 1 0 1 1 0

11/12/2023 35
Logical Operator > Example
 Example
 bool a = true;
 bool b = false;
 Console.WriteLine(a && b); // False
 Console.WriteLine(a || b); // True
 Console.WriteLine(a ^ b); // True
 Console.WriteLine(!b); // True
 Console.WriteLine(b || true); // True
 Console.WriteLine(b && true); // False
 Console.WriteLine(a || true); // True
 Console.WriteLine(a && true); // True
 Console.WriteLine(!a); // False
 Console.WriteLine((5>7) ^ (a==b)); // False
11/12/2023 36
Comparison Operators
 Comparison operators are used to compare variables
 ==, <, >, >=, <=, !=
 Comparison operators example:
int a = 5;
int b = 4;
Console.WriteLine(a >= b); // True
Console.WriteLine(a != b); // True
Console.WriteLine(a == b); // False
Console.WriteLine(a == a); // True
Console.WriteLine(a != ++b); // False
Console.WriteLine(a > b); // False
11/12/2023 37
Assignment Operators
 Assignment operators are used to assign a value to a
variable ,
 =, +=, -=, |=, ...
 Assignment operators example:
int x = 7;
int y = 4;
Console.WriteLine(y *= 2); // 8
int z = y = 3; // y=3 and z=3
Console.WriteLine(z); // 3
Console.WriteLine(x += 3); // 10
Console.WriteLine(x /= 2); // 5
11/12/2023 38
Other Operators
 String concatenation operator + is used to concatenate strings
 If the second operand is not a string, it is converted to string
automatically
 example
string name= “Name";
string fatherName= “Father Name";
Console.WriteLine(name + fatherName);
// Name FatherName
string output = "The number is : ";
int number = 5;
Console.WriteLine(output + number);
// The number is : 5
11/12/2023 39
Expressions
 Expressions are sequences of operators, literals and variables that are
evaluated to some value
 Expressions has:
 Type (integer, real, boolean, ...)
 Value
 Examples:
int r = (150-20) / 2 + 5; // r=70
// Expression for calculation of circle area
double surface = Math.PI * r * r;
// Expression for calculation of circle perimeter
double perimeter = 2 * Math.PI * r;
int a = 2 + 3; // a = 5
int b = (a+3) * (a-4) + (2*a + 7) / 4; // b = 12
bool greater = (a > b) || ((a == 0) && (b == 0));
11/12/2023 40
Using the Math Class
 Math class provides methods to work with numeral data
 Math.Round(decimalnumber[, precision, mode]);
 Math.Pow(number, power);
 Math.Sqrt(number);
 Math.Min(number1, number2);
 Math.Max(number1, number2);
 Example
double gpa = Math.Round(gpa,2);
double area = Math.Pow(radius, 2) * Math.PI; //area of a circle
double maxGpa = Math.Max(lastYearGpa, thisYearGpa);
double sqrtX = Math.Sqrt(x);
11/12/2023 41
Exercise
1. Write conditional expression (Ternary expression) that checks if given
integer is odd or even.
2. Write the output of the ff code fragment.
sbyte x = 9;
Console.WriteLine( "Shift of {0} is {1}.", x, ~x<<3);//shift of 9 is - 80.
3. Write the output of the ff code fragment.
ushort a = 3;
ushort b = 5;
Console.WriteLine(a ^ ~b);//-7
4. Write the output of the ff code fragment.
int a = 3;
int b = 5;
Console.WriteLine(“a + b = ” + a + b);
5. Write a program that calculates the area of a circle for a given radius r
(eqn: a).
11/12/2023 42
Console Input / Output
Reading and Writing to the Console

11/12/2023 43
Console Input / Output
 Printing to the Console
 Printing Strings and Numbers
 Reading from the Console
 Reading Characters
 Reading Strings
 Parsing Strings to Numeral Types
 Reading Numeral Types

11/12/2023 44
Printing to the Console
 Console is used to display information in a text window
 Can display different values:
 Strings
 Numeral types
 All primitive data types
 To print to the console use the namespace system and class
Console (System.Console)

11/12/2023 45
The Console Class
 Provides methods for console input and output
 Input
> Read(…) – reads a single character
> ReadKey(…) – reads a combination of keys
> ReadLine(…) – reads a single line of characters
 Output
> Write(…) – prints the specified argument on the console
> WriteLine(…) – prints specified data to the console and moves to the next
line

11/12/2023 46
Console.Write(…)
 Printing an integer variable
int a = 15;
...
Console.Write(a); // 15
 Printing more than one variable using a formatting string
double a = 15.5;
int b = 14;
...
Console.Write("{0} + {1} = {2}", a, b, a + b);
// 15.5 + 14 = 29.5
 Next print operation will start from the same line
11/12/2023 47
Console.WriteLine(…)
 Printing a string variable
string str = "Hello C#!";
...
Console.WriteLine(str);
 Printing more than one variable using a formatting string
string name = “Fatuma";
int year = 1990;
...
Console.WriteLine("{0} was born in {1}.", name, year);
// Fatuma was born in 1990.
 Next printing will start from the next line
11/12/2023 48
Reading from the Console
 Reading Strings and Numeral Types
 We use the console to read information from the command
line
 We can read:
 Characters
 Strings
 Numeral types (after conversion)
 To read from the console we use the methods
 Console.Read() and
 Console.ReadLine()
11/12/2023 49
Console.Read()
 Gets a single character from the console (after [Enter] is
pressed)
 Returns a result of type int
 Returns -1 if there aren’t more symbols
 To get the actually read character we
need to cast it to char
int i = Console.Read();
char ch = (char) i; // Cast the int to char
// Gets the code of the entered symbol
Console.WriteLine("The code of '{0}' is {1}.", ch, i);

11/12/2023 50
Console.ReadLine()
 Gets a line of characters
 Returns a string value
 Returns null if the end of the input is reached
Console.Write("Please enter your first name: ");
string firstName = Console.ReadLine();

Console.Write("Please enter your last name: ");


string lastName = Console.ReadLine();

Console.WriteLine("Hello, {0} {1}!", firstName, lastName);

11/12/2023 51
Reading Numeral Types
Numeral types can not be read directly from the console
To read a numeral type do the following:
1. Read a string value
2. Convert (parse) it to the required numeral type
int.Parse(string) – parses a string to int
string str = Console.ReadLine()
int number = int.Parse(str);
Console.WriteLine("You entered: {0}", number);
string s = "123";
int i = int.Parse(s); // i = 123
long l = long.Parse(s); // l = 123L
11/12/2023 52
Reading Numbers from the Console > Example
static void Main()
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());

Console.WriteLine("{0} + {1} = {2}", a, b, a+b);


Console.WriteLine ("{0} * {1} = {2}", a, b, a*b);
float f = float.Parse(Console.ReadLine());
Console.WriteLine("{0} * {1} / {2} = {3}", a, b, f, a*b/f);
}11/12/2023 53
Error Handling when Parsing
 Sometimes we want to handle the errors when parsing a number
 Two options: use TryParse() or try-catch block (later in Error Handling
Section)
 Parsing with TryParse():
string str = Console.ReadLine();
int number;
if (int.TryParse(str, out number)) // out is akey word
{
Console.WriteLine("Valid number: {0}", number);
}
else
{
Console.WriteLine("Invalid number: {0}", str);
}
11/12/2023 54
Console IO > Example
 Calculating an Area
Console.WriteLine("This program calculates the area of a rectangle or a
triangle");
Console.Write("Enter a and b (for rectangle) or a and h (for triangle): ");
//read inputs
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
Console.Write("Enter 1 for a rectangle or 2 for a triangle: ");
int choice = int.Parse(Console.ReadLine());
//calculate the area
double area = (double) (a*b) / choice;
//display the result
Console.WriteLine("The area of your figure is {0}", area);
11/12/2023 55
Conditional Statements
Implementing Control Logic in C#

11/12/2023 56
Conditional Statements
 Implementing Control Logic in C#
 if Statement
 if-else Statement
 nested if Statements
 multiple if-else-if-else-…
 switch-case Statement

11/12/2023 57
The if Statement
 The most simple conditional statement
 Enables you to test for a condition
 Branch to different parts of the code depending on the
result
 The simplest form of an if statement:
if (condition) false
condition
{
statements; true
} statement

11/12/2023 58
The if Statement > Example
static void Main()
{
Console.WriteLine("Enter two numbers.");

int biggerNumber = int.Parse(Console.ReadLine());


int smallerNumber = int.Parse(Console.ReadLine());

if (smallerNumber > biggerNumber)


{
biggerNumber = smallerNumber;
}

Console.WriteLine("The greater number is: {0}", biggerNumber);


}
11/12/2023 59
The if-else Statement
 More complex and useful conditional statement
 Executes one branch if the condition is true, and another if it is
false
 The simplest form of an if-else statement:
if (condition) false second
condition
{ statement
statement1; true
}
first
else statement
{
statement2;
}
11/12/2023 60
if-else Statement > Example
 Checking a number if it is odd or even
string s = Console.ReadLine();
int number = int.Parse(s);

if (number % 2 == 0)
{
Console.WriteLine("This number is even.");
}
else
{
Console.WriteLine("This number is odd.");
}
11/12/2023 61
Nested if Statements
 if and if-else statements can be nested, i.e. used inside another if or else
statement
 Every else corresponds to its closest preceding if
if (expression)
{
if (expression)
{
statement;
}
else
{
statement;
}
}
else
statement;
11/12/2023 62
Nested if Statements > Example
if (first == second)
{
Console.WriteLine("These two numbers are equal.");
}
else
{
if (first > second)
{
Console.WriteLine("The first number is bigger.");
}
else
{
Console.WriteLine("The second is bigger.");
}
}
11/12/2023 63
Multiple if-else-if-else-…
 Sometimes we need to use another if-construction in the else block
 Thus else if can be used:
int ch = 'X';
if (ch == 'A' || ch == 'a')
{
Console.WriteLine("Vowel [ei]");
}
else if (ch == 'E' || ch == 'e')
{
Console.WriteLine("Vowel [i:]");
}
else if …
else …
11/12/2023 64
The switch-case Statement
 Selects for execution a statement from a list depending on the
value of the switch expression
switch (day)
{
case 1: Console.WriteLine("Monday"); break;
case 2: Console.WriteLine("Tuesday"); break;
case 3: Console.WriteLine("Wednesday"); break;
case 4: Console.WriteLine("Thursday"); break;
case 5: Console.WriteLine("Friday"); break;
case 6: Console.WriteLine("Saturday"); break;
case 7: Console.WriteLine("Sunday"); break;
default: Console.WriteLine("Error!"); break;
}
11/12/2023 65
How switch-case Works?
1. The expression is evaluated
2. When one of the constants specified in a case label is equal
to the expression
 The statement that corresponds to that case is executed
3. If no case is equal to the expression
 If there is default case, it is executed
 Otherwise the control is transferred to the end point of the
switch statement

11/12/2023 66
switch-case > Usage good practice
 Variables types like string, enum and integral types can be used for switch
expression
 The value null is permitted as a case label constant
 The keyword break exits the switch statement
 "No fall through" rule – you are obligated to use break after each case
 Multiple labels that correspond to the same statement are permitted
 There must be a separate case for every normal situation
 Put the normal case first
 Put the most frequently executed cases first and the least frequently executed last
 Order cases alphabetically or numerically
 In default use case that cannot be reached under normal circumstances
11/12/2023 67
Looping/ Iterations Statements

Execute Blocks of Code Multiple Times

11/12/2023 68
Looping Statements
 A loop is a control statement that allows repeating execution of a block of
statements
 May execute a code block fixed number of times
 May execute a code block while given condition holds
 May execute a code block for each member of a collection
 Loops that never end are called an infinite loops
 Loops in C#
 while loops
 do … while loops
 for loops
 foreach loops
 Nested loops
11/12/2023 69
Using while(…) Loop
 Repeating a Statement While Given Condition Holds
 The simplest and most frequently used loop
while (condition)
{ false
condition
statements;
} true
 The repeat condition statement
 Returns a boolean result of true or false
 Also called loop condition

11/12/2023 70
While Loop > Example
int counter = 0;
while (counter < 10)
{
Console.WriteLine("Number : {0}", counter);
counter++;
}

11/12/2023 71
While Loop > Example
 Checking whether a number is prime or not
Console.Write("Enter a positive integer number: ");
uint number = uint.Parse(Console.ReadLine());
uint divider = 2;
uint maxDivider = (uint) Math.Sqrt(number);
bool prime = true;
while (prime && (divider <= maxDivider))
{
if (number % divider == 0)
{
prime = false;
}
divider++;
}
Console.WriteLine("Prime? {0}", prime);
11/12/2023 72
Do-While Loop
 Another loop structure is:
do
{ statement
statements; true
}
while (condition);
condition
 The block of statements is repeated
 While the boolean loop condition holds false
 The loop is executed at least once

11/12/2023 73
Do … while > Example
 Calculating N factorial
static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
int factorial = 1;

do
{
factorial *= n;
n--;
}
while (n > 0);

Console.WriteLine("n! = " + factorial);


}
11/12/2023 74
for loops
 The typical for loop syntax is:
for (initialization; test; update)
{
statements;
}

 Consists of
 Initialization statement
> Executed once, just before the loop is entered
 Boolean test expression
> Evaluated before each iteration of the loop
 If true, the loop body is executed
 If false, the loop body is skipped
 Update statement
> Executed at each iteration after the body of the loop is finished
 Loop body block
11/12/2023 75
for Loop > Example
 A simple for-loop to print the numbers 0…9:
for (int number = 0; number < 10; number++)
{
Console.Write(number + " ");
}
 A simple for-loop to calculate n!:
decimal factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
11/12/2023 76
foreach Loop
 Iteration over a Collection
 The typical foreach loop syntax is:
foreach (Type element in collection)
{
statements;
}
 Iterates over all elements of a collection
 The element is the loop variable that takes sequentially all collection
values
 The collection can be list, array or other group of elements of the same
type
11/12/2023 77
foreach Loop > Example
 Example of foreach loop:
string[] days = new string[] {
"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" };
foreach (string day in days)
{
Console.WriteLine(day);
}
 The above loop iterates of the array of days
 The variable day takes all its values

11/12/2023 78
Nested Loops
 A composition of loops is called a nested loop
 A loop inside another loop
 Example:
for (initialization; test; update)
{
for (initialization; test; update)
{
statements;
}

}

11/12/2023 79
Nested loop > Example
 Print the following triangle:
1
1 2

1 2 3 ... n
int n = int.Parse(Console.ReadLine());
for(int row = 1; row <= n; row++)
{
for(int column = 1; column <= row; column++)
{
Console.Write("{0} ", column);
}
Console.WriteLine();
}
11/12/2023 80
C# Jump Statements
 Jump statements are:
break, continue, goto, return
 How continue woks?
In while and do-while loops jumps to the test expression
In for loops jumps to the update expression
 To exit an inner loop use break
 To exit outer loops use goto with a label
 Avoid using goto! (it is considered harmful)
return – to terminate method execution and go back to the caller
method
11/12/2023 81
Jump Statements > Example
int outerCounter = 0;
for (int outer = 0; outer < 10; outer++)
{
for (int inner = 0; inner < 10; inner++)
{
if (inner % 3 == 0)
continue;
if (outer == 7)
break;
if (inner + outer > 9)
goto breakOut;
}
outerCounter++;
}
breakOut:
11/12/2023 82
Jump Statements > continue example
 Example: sum all odd numbers in [1, n] that are not divisors of 7:
int n = int.Parse(Console.ReadLine());
int sum = 0;
for (int i = 1; i <= n; i += 2)
{
if (i % 7 == 0)
{
continue;
}
sum += i;
}
Console.WriteLine("sum = {0}", sum);
11/12/2023 83
For more information
 Brian Bagnall, et al. C# for Java Programmers. USA. Syngress
Publishing, Inc.
 http://www.tutorialspoint.com/csharp/
 Svetlin Nakov et al. Fundamentals of Computer Programming
With C#. Sofia, 2013
 Joel Murach, Anne Boehm. Murach C# 2012, Mike Murach &
Associates Inc USA, 2013

11/12/2023 84
Date and string data types
Working with Date and string data types

11/12/2023 85
Dates and Times
 Data processing on date and time values
 DateTime structure of .Net framework provides a variety of properties and methods for
 Getting information about dates and times
 Formatting date and time values
 Performing operations on dates and times
 To create a DateTime value
 Use new key word
 Specify the date and time values

Syntax:
DateTime variable = new DateTime(year, month, day[, hour, minute, second[, millisecond]]);

 If time is not specified, it set to 12:00 AM.


 Use also static Parse and TryParse method to create DateTime value from a string
DateTime variable = DateTime.Parse(string);
DateTime variable;
DateTime.TryParse(string, out variable);
11/12/2023 86
Dates and Times > Example
DateTime startDate = new DateTime(2019, 04, 30); //
DateTime startDateTime = new DateTime(2019, 01, 30, 13, 30, 0); //
DateTime startDate = DateTime.Parse(“03/08/16”); //
DateTime startDate = DateTime.Parse (“Apr 08, 2019 1:30 PM”); //
DateTime dateOfBirth= DateTime.Parse (Console.ReadLine()); //
DateTime expDate;
DateTime.TryParse (Console.ReadLine(), out expDate); //
DateTime deadlineDate;
Console.WriteLine(“Enter deadline Date (mm/dd/yyyy) :”);
deadlineDate = Convert.ToDateTime(Console.ReadLine());

11/12/2023 87
Dates and Times > Date and Time writing format
 Valid date format includes:
 04/30/2019
 1/30/19
 01-30-2019
 1-30-19
 2019-30-1
 Jan 30 2019
 January 30, 2019
 Valid time format includes:-
 2:15 PM
 14:15
 02:15:30 AM
11/12/2023 88
Dates and Times > Current Date and Time
 Use two static properties of DateTime structure to get the
current date/time
 Now
> Returns the current date and time
 Today
> Returns the current date
 Example
DateTime currDateTime = DateTime.Now; //
DateTime currDate = DateTime.Today; //
DateTime regDateTime = DateTime.Toady;
DateTime modifiedDate = DateTime.Now;

11/12/2023 89
Dates and Times > Date and Time formatting
 The format depends on the computer regional setting
 Use the methods of DateTime structure to format the date/time in the
way you want
 ToLongDateString()
 Name for the day of the week, the name for the month, the date of the
month, and the year
 ToShortDateString()
 The numbers for the month, day, and year
 ToLongTimeString()
 The hours, minutes and seconds
 ToShortTimeString()
 The hours and minutes
11/12/2023 90
Dates and Times > Date and Time formatting >Example
 Statements that format dates and times data
DateTime currDateTime = DateTime.Now;
string longDate = currDateTime.ToLongDateString(); //
string shortDate = currDateTime.ToShortDateString(); //
string longTime = currDateTime.ToLongTimeString(); //
string shortDate = currDateTime.ToShortTimeString(); //

11/12/2023 91
Dates and Times > Getting information about Dates and Times
 The DateTime structure provides a variety of properties and methods for getting information about
dates and times

11/12/2023 92
Getting information about Dates and Times > Example
DateTime currDateTime = DateTime.Now;
int month = currDateTime.Month;
int hour = currDateTime.Hour;
int dayOfYear = currDateTime.DayOfYear;
int daysInMonth = DateTime.DaysInMonth(currDateTime.Year, 2);
bool isLeapYear = currDateTime.IsLeapYear();
DayOfWeek dayOfWeek = currDateTime.DayOfWeek;
string message=“”:
if(dayOfWeek == DayOfWeek.Saturday || dayOfWeek == DayOfWeek.Sunday ) {
message = “Weekend”;
}
else {
message = “Week day”;
}
11/12/2023 93
Dates and Times > Perform Operations on Dates and Times
 Methods for performing operations on dates and times

11/12/2023 94
Perform Operations on Dates and Times > Example
DateTime dateTime = DateTime.Parse(“1/3/2016 13:30”);
DateTime dueDate = dateTime.AddMonths(2);
dueDate = dateTime.AddDays(60);
DateTime runTime = dateTime.AddMinutes(30);
runTime = dateTime.AddHours(10);
DateTime currentDate = DateTime.Today;
DateTime deadLine = DateTime.Parse(“3/15/2016”);
TimeSpan timeTillDeadline = deadLine.Subtract(currentDate);
int daysTillDeadline = timeTillDeadline.Days;
TimeSpan timeTillDeadline = deadLine – currentDate;
double totalDaysTillDeadline = timeTillDeadline.TotalDays;
int hoursTillDeadline= timeTillDeadline.Hours;
int minutesTillDeadline= timeTillDeadline.Minutes;
int secondsTillDeadline= timeTillDeadline.Seconds;
bool passedDeadline = false;
if(currentDate > deadLine ){
passedDeadline = true;
}
11/12/2023 95
Format dates and times
 Use Format methods of the String class to format dates and times
 Standard DateTime formatting

11/12/2023 96
Format dates and times …
 Custom DateTime formatting

11/12/2023 97
Format dates and times > Example
DateTime currDate = DateTime.Now;
string formattedDate = “”;
formattedDate = String.Format(“{0:d}”, currDate);
formattedDate = String.Format(“{0:D}”, currDate);
formattedDate = String.Format(“{0:t}”, currDate);
formattedDate = String.Format(“{0:T}”, currDate);
formattedDate = String.Format(“{0:ddd, MMM d, yyyy}”, currDate);
formattedDate = String.Format(“{0:M/d/yy}”, currDate);
formattedDate = String.Format(“{0:HH:mm:ss}”, currDate);

11/12/2023 98
Working with Strings
Processing and Manipulating Text Information

11/12/2023 99
Working with Strings
 Working with characters in a string
 Working with string – creating string object from String class
 Use properties and methods of String class to work with string
object
 StringBuilder class also provides another properties and methods
to work with string

11/12/2023 100
Properties and methods of String class
 Common properties and methods of String class
 [index] – gets the character at the specified position
 Length – gets the number of characters
 StartsWith(string)
 EndsWidth(string)
 IndexOf(string[, startIndex])
 LastIndexOf(string[, startIndex])
 Insert(startIndex, string)
 PadLeft(totalWidth)
 PadRight(totalWidth)
 Remove(startIndex, count)
 Replace(oldString, newString)
 Substring(startIndex[, length])
 ToLower()
 ToUpper()
 Trim()
 Split(splitCharacters)
 Use an index to access each character in a string where 0 in the index for the first character, 1 the index for the
second character, …
11/12/2023 101
Using StringBuilder class
 StringBuilder objects are mutable, means they can be changed, deleted, replaced, modified
 Syntax
 StringBuilder var = new StringBuilder([value] [, ] [capacity]); // default capacity is 16 characters

11/12/2023 102
StringBuilder > Example
 StringBuilder address1 = new StringBuilder();
 StringBuilder address2 = new StringBuilder(10);
 StringBuilder phone1= new StringBuilder(“0912345678”);
 StringBuilder phone2 = new StringBuilder(“0912345678”, 10);
 StringBuilder phoneNumber = new StringBuilder(10);
 phoneNumber.Append(“0912345678”);
 phoneNumber.Insert(0, “(+251)”);
 phoneNumber.Insert(4, “.”);
 phoneNumber.Replace(“.”, “-”);
 phoneNumber.Remove(0,
11/12/2023
4); 103
Manipulating Strings
Comparing, Concatenating, Searching, Extracting Substrings, Splitting

11/12/2023 104
Comparing Strings
 A number of ways exist to compare two strings:
 Dictionary-based string comparison
> Case-insensitive
 int result = string.Compare(str1, str2, true);
 // result == 0 if str1 equals str2
 // result < 0 if str1 is before str2
 // result > 0 if str1 is after str2
> Case-sensitive
 string.Compare(str1, str2, false);

 Equality checking by operator ==


 Performs case-sensitive compare
> if (str1 == str2)
> {
> …
> }

 Using the case-sensitive Equals() method


 The same effect like the operator ==
> if (str1.Equals(str2))
> {
> …
> }
11/12/2023 105
Comparing Strings – Example
 Finding the first string in alphabetical order from a given list of strings:
string[] towns = {“Hawassa", “Dilla", “Adama",
“Mekele", “Debre Berhan", “Dessie", “Gonder"};
string firstTown = towns[0];
for (int i=1; i<towns.Length; i++)
{
string currentTown = towns[i];
if (String.Compare(currentTown, firstTown) < 0)
{
firstTown = currentTown;
}
}
Console.WriteLine("First town: {0}", firstTown);
11/12/2023 106
Concatenating Strings
 There are two ways to combine strings:
 Using the Concat() method
> string str = String.Concat(str1, str2);
 Using the + or the += operators
> string str = str1 + str2 + str3;
> string str += str1;
 Any object can be appended to string
> string name = “Lemma";
> int age = 22;
> string s = name + " " + age; // Lemma 22

11/12/2023 107
Concatenating Strings – Example
string firstName = “Soliana";
string lastName = “Abesselom";

string fullName = firstName + " " + lastName;


Console.WriteLine(fullName);// Soliana Abesselom

int age = 25;


string nameAndAge ="Name: " + fullName + "\nAge: " + age;
Console.WriteLine(nameAndAge);
// Name: Soliana Abesselom
// Age: 25

11/12/2023 108
Searching in Strings
 Finding a character or substring within given string
 First occurrence
> IndexOf(string str);
 First occurrence starting at given position
> IndexOf(string str, int startIndex)
 Last occurrence
> LastIndexOf(string)
 IndexOf is case-sensetive

11/12/2023 109
Searching in Strings > Example
 string str = "C# Programming Course";
 int index = str.IndexOf("C#");
 index = str.IndexOf("Course");
 index = str.IndexOf("COURSE");
 index = str.IndexOf("ram");
 index = str.IndexOf("r");
 index = str.IndexOf("r", 5);
 index = str.IndexOf("r", 8);

11/12/2023 110
Extracting Substrings
 Extracting substrings
 str.Substring(int startIndex, int length)
> string filename = @"C:\Pics\bird2009.jpg";
> string name = filename.Substring(8, 8);
 str.Substring(int startIndex)
> string filename = @"C:\Pics\Summer2009.jpg";
> string nameAndExtension = filename.Substring(8);
> // nameAndExtension is Summer2009.jpg

11/12/2023 111
Splitting Strings
 To split a string by given separator(s) use the following method:
 string[] Split(params char[])
string listOfBeers = “Bedelle, Habesha Raya, Dashen Giorgis, Meta";
string[] beers = listOfBeers.Split(' ', ',', '.');
Console.WriteLine("Available beers are:");
foreach (string beer in beers)
{
Console.WriteLine(beer);
}

11/12/2023 112
Trimming White Space
 Using method Trim()
 string s = " example of white space ";
 string clean = s.Trim();
 Console.WriteLine(clean);
 Using method Trim(chars)
 string s = " \t\nHello!!! \n";
 string clean = s.Trim(' ', ',' ,'!', '\n','\t');
 Console.WriteLine(clean); //
 Using TrimStart() and TrimEnd()
 string s = " C# ";
 string clean = s.TrimStart(); // clean =
11/12/2023 113
For more information
 http://www.tutorialspoint.com/csharp/
 Svetlin Nakov et al. Fundamentals of Computer Programming
With C#. Sofia, 2013
 Joel Murach, Anne Boehm. Murach C# 2012, Mike Murach &
Associates Inc USA, 2013

11/12/2023 114
Methods, events and delegates
Subroutines in Computer Programming

11/12/2023 115
Methods
 A method is a kind of building block that solves a small
problem
 A piece of code that has a name and can be called from the other
code
 Can take parameters and return a value
 Can be public or private
 Methods allow programmers to construct large programs
from simple pieces
 Methods are also known as functions, procedures, and
subroutines
11/12/2023 116
Why to Use Methods?
 More manageable programming
 Split large problems into small pieces
 Better organization of the program
 Improve code readability
 Improve code understandability
 Avoiding repeating code
 Improve code maintainability
 Code reusability
 Using existing methods several times

11/12/2023 117
Declaring and Creating methods
 Each Method has
 Name
 Access modifier
 Return type
 Parameters/arguments
 A body /statements
Syntax
access_modifier return_type name(parametrs){
statements;
}
example
public double CalculateGpa(double totalGradePoint, int totalCredit){
return totalGradePoint/totalCredit;
}
11/12/2023 118
Calling Methods
 To call a method, simply use:
 The method’s name
 Pass value
 Accept return value if any
 Example
 double cgpa = calculateGpa(92.23, 36);

11/12/2023 119
Passing parameters by value and reference
 When calling a method, each argument can be passed by value or by reference
 Pass by value
 Original value will not be changed by the calling method
 Pass by reference
 Original value can be changed by the calling method
 to pass by reference use
> ref or
> out keyword
 No need to initialize the argument, assign value to it within the calling method

 Example
void PrintSum(int start; int end, int ref sum)
{

for (int i=start; i<=end; i++)


{
sum+=I;
}
}
//
int sum =0;
PrintSum(start, end, ref sum);
Console.WriteLine(“Sum {0}”, sum);
11/12/2023 120
Recursive methods
 The Power of Calling a Method from Itself
 Example
static decimal Factorial(decimal num)
{
if (num == 0)
return 1;
else
return num * Factorial(num - 1);
}

11/12/2023 121
Events, delegates and Indexer
 Events are user actions such as key press, clicks, mouse movements,
etc., or some occurrence such as system generated notifications.
 Applications need to respond to events when they occur.
 For example, interrupts.
 Events are used for inter-process communication.
 A delegate is a reference type variable that holds the reference to a
method.
 The reference can be changed at runtime.
 An indexer allows an object to be indexed such as an array.
 When you define an indexer for a class, this class behaves similar to a
virtual array.
 Reading assignment about Events, delegates and Indexer
11/12/2023 122
Object Oriented Programming
Modeling Real-world Entities with Objects

11/12/2023 123
Objects
 Software objects model real-world objects or abstract concepts
 Examples:
> bank, account, customer, dog, bicycle, queue
 Real-world objects have states and behaviors
 Account' states:
> holder, balance, type
 Account' behaviors:
> withdraw, deposit, suspend
 How do software objects implement real-world objects?
 Use variables/data to implement states
 Use methods/functions to implement behaviors
 An object is a software bundle of variables and related methods
11/12/2023 124
Class
 Classes act as templates from which an instance of an object
is created at run time.
 Classes define the properties of the object and the methods
used to control the object's behavior.
 By default the class definition encapsulates, or hides, the
data inside it.
 Key concept of object oriented programming.
 The outside world can see and use the data only by calling
the build-in functions; called “methods”
 Methods and variables declared inside a class are called
members of that class.
11/12/2023 125
Objects vs Class
 An instance of a class is called an object.
 Classes provide the structure for objects
 Define their prototype, act as template Account

 Classes define: +Owner: Person


+Ammount: double
 Set of attributes
> Represented by variables and properties +Suspend()
> +Deposit(sum:double)
Hold their state
+Withdraw(sum:double)
 Set of actions (behavior)
> Represented by methods
 A class defines the methods and types of data associated
with
11/12/2023
an object 126
Classes in C#
 An object is a concrete instance of a particular class
 Creating an object from a class is called instantiation
 Objects have state
 Set of values associated to their attributes
 Example:
 Class: Account
 Objects: Abebe's account, Kebede's account

11/12/2023 127
Classes in C#
 Basic units that compose programs
 Implementation is encapsulated (hidden)
 Classes in C# can contain:
 Access Modifiers
 Fields (member variables)
 Properties
 Methods
 Constructors
 Inner types
 Etc. (events, indexers, operators, …)
11/12/2023 128
Classes in C#
 Classes in C# could have following members:
 Fields, constants, methods, properties, indexers, events, operators,
constructors, destructors
 Inner types (inner classes, structures, interfaces, delegates, ...)
 Members can have access modifiers (scope)
 public, private, protected, internal
 Members can be
 static (common) or specific for a given object

11/12/2023 129
Classes in C# – Examples
 Example of classes:
 System.Console
 System.String (string in C#)
 System.Int32 (int in C#)
 System.Array
 System.Math
 System.Random

11/12/2023 130
Simple Class Definition
public class Cat {
private string name;
private string owner;
public Cat(string name, string owner)
{
this.name = name;
this.owner = owner;
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Owner
{
get { return owner;}
set { owner = value; }
}
public void SayMiau()
{
Console.WriteLine("Miauuuuuuu!");
}
}
11/12/2023 131
Access Modifiers
 Class members can have access modifiers
 Used to restrict the classes able to access them
 Supports the OOP principle "encapsulation"
 Class members can be:
 public – accessible from any class
 protected – accessible from the class itself and all its descendent
classes
 private – accessible from the class itself only
 internal – accessible from the current assembly (used by default)

11/12/2023 132
Fields and Properties
 Fields are data members of a class
 Can be variables and constants
 Accessing a field doesn’t invoke any actions of the object
 Example:
 String.Empty (the "" string)
 Constant fields can be only read
 Variable fields can be read and modified
 Usually properties are used instead of directly accessing variable fields
 // Accessing read-only field
 String empty = String.Empty;
 // Accessing constant field
 int maxInt = Int32.MaxValue;
11/12/2023 133
Properties
 Properties look like fields (have name and type), but they can contain code,
executed when they are accessed
 Usually used to control access to data
fields (wrappers), but can contain more complex logic
 Can have two components (and at least one of them) called accessors
 get for reading their value
 set for changing their value
 According to the implemented accessors properties can be:
 Read-only (get accessor only)
 Read and write (both get and set accessors)
 Write-only (set accessor only)
 Example of read-only property:
 String.Length
11/12/2023 134
The Role of Properties
 Expose object's data to the outside world
 Control how the data is manipulated
 Properties can be:
 Read-only
 Write-only
 Read and write
 Give good level of abstraction
 Make writing code easier
 Properties should have:
 Access modifier (public, protected, etc.)
 Return type
 Unique name
 Get and / or Set part
 Can contain code processing data in specific way
11/12/2023 135
Defining Properties – Example
public class Point
{
private int xCoord;
private int yCoord;
public int XCoord
{
get { return xCoord; }
set { xCoord = value; }
}
public int YCoord
{
get { return yCoord; }
set { yCoord = value; }
}
// More code ...
}
11/12/2023 136
Instance and Static Members
 Fields, properties and methods can be:
 Instance (or object members)
 Static (or class members)
 Instance members are specific for each object
 Example: different dogs have different name
 Static members are common for all instances of a class
 Example: DateTime.MinValue is shared between all instances of
DateTime

11/12/2023 137
Instance and Static Members – Examples
 Example of instance member
 String.Length
> Each string object has different length

 Example of static member


 Console.ReadLine()
> The console is only one (global for the program)
> Reading from the console does not require to create an instance of it

11/12/2023 138
Static vs. Non-Static
 Static:
 Associated with a type, not with an instance
 Non-Static:
 The opposite, associated with an instance
 Static:
 Initialized just before the type is used for the first time
 Non-Static:
 Initialized when the constructor is called

11/12/2023 139
Methods
 Methods manipulate the data of the object to which they belong
or perform other tasks
 Examples:
 Console.WriteLine(…)
 Console.ReadLine()
 String.Substring(index, length)
 Array.GetLength(index)

11/12/2023 140
Static Methods
 Static methods are common for all instances of a class (shared
between all instances)
 Returned value depends only on the passed parameters
 No particular class instance is available
 Syntax:
 The name of the class, followed by the name of the method, separated
by dot
 <class_name>.<method_name>(<parameters>)

11/12/2023 141
Interface vs. Implementation
 The public definitions comprise the interface for the class
 A contract between the creator of the class and the users of the class.
 Should never change.
 Implementation is private
 Users cannot see.
 Users cannot have dependencies.
 Can be changed without affecting users.

11/12/2023 142
Constructors
 is a method with the same name as the class.
 It is invoked when we call new to create an instance of a class.
 In C#, unlike C++, you must call new to create an object.
 Just declaring a variable of a class type does not create an object.
 Example
class Student{
private string name;
private fatherName;
public Student(string n, string fn){
name = n;
fatherName = fn;
}
}
 If you don’t write a constructor for a class, the compiler creates a default constructor.
 The default constructor is public and has no arguments.
11/12/2023 143
Multiple Constructors
 A class can have any number of constructors.
 All must have different signatures.
 The pattern of types used as arguments
 This is called overloading a method.
 Applies to all methods in C#.
 Not just constructors.
 Different names for arguments don’t matter, Only the types.

11/12/2023 144
Structures
 Structures are similar to classes
 Structures are usually used for storing data structures, without
any other functionality
 Structures can have fields, properties, etc.
 Using methods is not recommended
 Structures are value types, and classes are reference types
Example of structure
 System.DateTime – represents a date and time

11/12/2023 145
Namespaces
 Organizing Classes Logically into Namespaces
 Namespaces are used to organize the source code into more logical and manageable
way
 Namespaces can contain
 Definitions of classes, structures, interfaces and other types and other namespaces
 Namespaces can contain other namespaces
 For example:
 System namespace contains Data namespace
 The name of the nested namespace is System.Data
 A full name of a class is the name of the class preceded by the name of its namespace
 Example:
 Array class, defined in the System namespace
 The full name of the class is System.Array
11/12/2023 146
Including Namespaces
 The using directive in C#:
 using <namespace_name>
 Allows using types in a namespace, without specifying their full
name
 Example:
 using System;
 DateTime date;
 instead of
 System.DateTime date;

11/12/2023 147
Generic Classes
 Parameterized Classes and Methods
 Generics allow defining parameterized classes that process data
of unknown (generic) type
 The class can be instantiated with several different particular types
 Example: List<T>  List<int> / List<string> /
List<Student>
 Generics are also known as "parameterized types" or "template
types"
 Similar to the templates in C++
 Similar to the generics in Java
11/12/2023 148
Generics – Example
public class GenericList<T>
{
public void Add(T element) { … }
}
class GenericListExample
{
static void Main()
{
// Declare a list of type int
GenericList<int> intList = new GenericList<int>();
// Declare a list of type string
GenericList<string> stringList = new GenericList<string>();
}
}
11/12/2023 149
For more information
 http://www.tutorialspoint.com/csharp/
 Svetlin Nakov et al. Fundamentals of Computer Programming
With C#. Sofia, 2013
 Joel Murach, Anne Boehm. Murach C# 2012, Mike Murach &
Associates Inc USA, 2013

11/12/2023 150
Collections
Processing Sequences of Elements and set of elements

11/12/2023 151
Array
 An array is a sequence of elements
C# Array Types
 All elements are of the same type
There are 3 types of arrays in C# programming:
 The order of the elements is fixed
 Has fixed size (Array.Length)  Single Dimensional Array
 Zero based index  Multidimensional Array
 Is reference type  Jagged Array
 Declaration - defines the type of the elements
 Square brackets [] mean "array"
 Examples:
> int[] myIntArray;
> string[] myStringArray;
 Use the operator new
> Specify array length
> int [] myIntArray = new int[5];
 Creating and initializing can be done together:
> int [] myIntArray = {1, 2, 3, 4, 5}; or int [] myintArray = new int[] {1, 2, 3, 4, 5}; or int [] myintArray = new int[5] {1, 2, 3, 4, 5};
 The new operator is not required when using curly brackets initialization
 C# provides automatic bounds checking for arrays
11/12/2023 152
Creating Array > Example
 Creating an array that contains the names of the days of the
week
string[] daysOfWeek =
{
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
};
11/12/2023 153
Accessing Array Elements
 Read and Modify Elements by Index
 Array elements are accessed using the square brackets operator
[] (indexer)
 Array indexer takes element’s index as parameter
 The first element has index 0
 The last element has index Length-1
 Array elements can be retrieved and changed by the [] operator

11/12/2023 154
Accessing Array Elements > Example
 Reading Arrays From the Console
 First, read from the console the length of the array
int n = int.Parse(Console.ReadLine());
 Next, create the array of given size and read its elements in a for loop
int[] arr = new int[n];
for (int i=0; i<n; i++)
{
arr[i] = int.Parse(Console.ReadLine());
}
 Print each element to the console
string[] array = {"one", "two", "three"};
// Process all elements of the array
for (int index = 0; index < array.Length; index++)
{
// Print each element on a separate line
Console.WriteLine("element[{0}] = {1}",
index, array[index]);
}
11/12/2023 155
Accessing Array Elements > Example
 Printing array of integers in reversed order:
int[] array ={12,52,83,14,55};
Console.WriteLine("Reversed: ");
for (int i = array.Length-1; i >= 0; i--)
{
Console.Write(array[i] + " ");
}
 Print all elements of a string[] array using foreach:
string[] cities= { “Adama”, “Hawassa", “Debre Berhan", “Bahir Dar", “Mekelle"};
foreach (string city in cities)
{
Console.WriteLine(city);
}
11/12/2023 156
Multidimensional Arrays
 Using Array of Arrays, Matrices and Cubes
 Multidimensional arrays have more than one dimension (2, 3, …)
 The most important multidimensional arrays are the 2-dimensional
> Known as matrices or tables
 Declaring multidimensional arrays:
int[,] intMatrix;
float[,] floatMatrix;
string[,,] strCube;
 Creating a multidimensional array
 Use new keyword
 Must specify the size of each dimension
int[,] intMatrix = new int[3, 4];
float[,] floatMatrix = new float[8, 2];
string[,,] stringCube = new string[5, 5, 5];
 Creating and initializing with values multidimensional array:
int[,] matrix =
{
{1, 2, 3, 4}, // row 0 values
{5, 6, 7, 8}, // row 1 values
}; // The matrix size is 2 x 4 (2 rows, 4 cols)
11/12/2023 157
Multidimensional Arrays > Example
 Reading a matrix from the console
int rows = int.Parse(Console.ReadLine());
int cols= int.Parse(Console.ReadLine());
int[,] matrix = new int[rows, cols];
String inputNumber;
for (int row=0; row<rows; row++)
{
for (int col=0; col<cols; col++)
{
Console.Write("matrix[{0},{1}] = ", row, col);
inputNumber = Console.ReadLine();
matrix[row, col] = int.Parse(inputNumber);
}
}
11/12/2023 158
Multidimensional Arrays > Example
 Printing a matrix on the console:
for (int row=0; row<matrix.GetLength(0); row++)
{
for (int col=0; col<matrix.GetLength(1); col++)
{
Console.Write("{0} ", matrix[row, col]);
}
Console.WriteLine();
}

11/12/2023 159
Multidimensional Arrays > Example
 Finding a 2 x 2 platform in a matrix with a maximal sum of its elements
int[,] matrix = {
{7, 1, 3, 3, 2, 1},
{1, 3, 9, 8, 5, 6},
{4, 6, 7, 9, 1, 0}
};
int bestSum = int.MinValue;
for (int row=0; row<matrix.GetLength(0)-1; row++)
for (int col=0; col<matrix.GetLength(1)-1; col++)
{
int sum = matrix[row, col] + matrix[row, col+1]
+ matrix[row+1, col] + matrix[row+1, col+1];
if (sum > bestSum)
bestSum = sum;
}
11/12/2023 160
Array Functions
 Array is a class; hence provides properties and methods to work with it
 Property
 Length – gets the number of elements in all the dimension of array
 Methods
 GetLength(dimension) - gets the number of elements in the specified dimension of an array
 GetUpperBound(dimension) – Gets the index of the last elements in the specified
dimension of an array
 Copy(array1, array2, length) – Copies some or all of the values in one array to another array.
 BinarSearch(array, value) – Searches a one-dimensional array that’s in ascending order and
returns the index for a value
 Sort(array) – Sorts the elements of a one dimensional array in to ascending order
 Clear(array, start, end) – clears elements of an array
 Reverse(array) - reverses the elements of an array
 The BinarySearch method only works on arrays whose elements are in ascending
order
11/12/2023 161
Array Function > Example
int [] number = new int [4] {1,2,3,4,5};
int len = numbers.GetLength(0);
int upperBound = numbers.GetUpperBound(0);
//
string[] names = {“Abebe”, “Kebede”, “Soliana”, “Fatuma”, “Makida”};
Array.Sort(names);
foreach(string name in names)
Console.WriteLine(name);
//
decimal[] sales = {15463.12m, 25241.3m, 45623.45m, 41543.23m,
40521.23m};
int index = Array.BinarySearch(names, “Soliana”);
decimal sale = sales[index];
11/12/2023 162
Copying Arrays
 Sometimes we may need to copy the values from one array to
another one
 If we do it the intuitive way we would copy not only the values but the
reference to the array
 Changing some of the values in one array will affect the other
> int[] copyArray=array;
 The way to avoid this is using Array.Copy()
> Array.Copy(sourceArray, copyArray);
 This way only the values will be copied but not the reference
 Reading assignment : How to work with Jagged arrays

11/12/2023 163
List<T>
 Lists are arrays that resize dynamically
When adding or removing elements
> use indexers ( like Array)
T is the type that the List will hold
> E.g.
 List<int> will hold integers
 List<object> will hold objects

 Basic Methods and Properties


Add(T element) – adds new element to the end
Remove(element) – removes the element
Count – returns the current size of the List

11/12/2023 164
List > Example
List<int> intList=new List<int>();
for( int i=0; i<5; i++)
{
intList.Add(i);
}
 Is the same as
int[] intArray=new int[5];
for( int i=0; i<5; i++)
{
intArray[i] = i;
}
 The main difference
 When using lists we don't have to know the exact number of elements
11/12/2023 165
Lists vs. Arrays
 Lets have an array with capacity of 5 elements
int[] intArray=new int[5];
 If we want to add a sixth element ( we have already added 5) we have
to do
int[] copyArray = intArray;
intArray = new int[6];
for (int i = 0; i < 5; i++)
{
intArray[i] = copyArray[i];
}
intArray[5]=newValue;
 With List we simply do
list.Add(newValue);
11/12/2023 166
ArrayList
 It represents ordered collection of an object that can be indexed
individually.
 It is basically an alternative to an array.
 However, unlike array you can add and remove items from a list
at a specified position using an index and the array resizes itself
automatically.
ArrayList arrayList = new ArrayList();
 It can contain a mixed content as object
 It also allows dynamic memory allocation, adding, searching and
sorting items in the list.
11/12/2023 167
ArrayList > Example
ArrayList al = new ArrayList();
Console.WriteLine("Adding some numbers:");
ArrayList arrrayList = new ArrayList();
al.Add(45);
al.Add(78); arrrayList.Add(“One”);
al.Add(33);
al.Add(56); arrrayList.Add(2);
al.Add(12);
al.Add(23); arrrayList.Add(“Three”);
al.Add(9);
Console.WriteLine("Capacity: {0} ", al.Capacity); arrrayList.Add(4);
Console.WriteLine("Count: {0}", al.Count);
Console.Write("Content: "); int number = 0;
foreach (int i in al)
{ foreach(object obj in araayList)
Console.Write(i + " ");
} {
Console.WriteLine();
Console.Write("Sorted Content: ");
If(obj is int)
al.Sort(); {
foreach (int i in al)
{
number += (int) obj;
Console.Write(i + " "); }
}
Console.WriteLine(); }
11/12/2023 168
Enumeration - enum
 Enumeration is a set of related constants that define a value type
 Each constant is a member of the enumeration
 syntax
enum enumName [: type]
{
ConstantName1 [= value1],
ConstantName2 [=value2], …
}
 Example
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
int WeekdayStart = (int)Days.Mon;
int WeekdayEnd = (int)Days.Fri;
Console.WriteLine("Monday: {0}", WeekdayStart);
Console.WriteLine("Friday: {0}", WeekdayEnd);
11/12/2023 169
Dictionaries
 Dictionaries are used to associate a a particular key with a given
value
 In C#, defined by Hashtable class
 It uses a key to access the elements in the collection.
 A hash table is used when you need to access elements by using
key, and you can identify a useful key value.
 Each item in the hash table has a key/value pair.
 The key is used to access the items in the collection.
 Key must be unique
 Do not have any sense of order
11/12/2023 170
Hashtable > Example
Hashtable ht = new Hashtable();
ht.Add("001", “Abe Kebe");
ht.Add("002", “Alem Selam");
ht.Add("003", “Fatuma Ahmed");
ht.Add("004", “Soliana Abesselom");
ht.Add("005", “Tigist Abrham");
ht.Add("006", “Selam Ahmed");
ht.Add("007", “Makida Birhanu");
if (ht.ContainsValue(" Selam Ahmed "))
{
Console.WriteLine("This student name is already in the list");
}
else
{
ht.Add("008", " Selam Ahmed ");
}
// Get a collection of the keys.
ICollection key = ht.Keys;
foreach (string k in key)
{
Console.WriteLine(k + ": " + ht[k]);
}
11/12/2023 171
Stacks
 Stack also maintain a list of items like array and ArrayList, but
 Operates on a push-on and pop-off paradigm
 Stacks are LIFO – Last In First Out
Stack stack = new Stack();
stack.Push(“item”); // insert item on the top
object obj = stack.Pop(); // gets top item
object obp = stack.Peek() // looks at top
int size = stack.Count; //gets the number of items in the stack

11/12/2023 172
Queues
 Queues maintain a list of items like stack, but
 Operate with a principle of FIFO – First In First Out

Queue queue = new Queue();


queue.Enqueue(“item”); //insert an item to the last
object obj = queue.Dequeue(); // gets first item
int size = queue.Count; // gets number of items

11/12/2023 173
For more information
 Brian Bagnall, et al. C# for Java Programmers. USA. Syngress
Publishing, Inc.
 Svetlin Nakov et al. Fundamentals of Computer Programming
With C#. Sofia, 2013
 Joel Murach, Anne Boehm. Murach C# 2012, Mike Murach &
Associates Inc USA, 2013

11/12/2023 174
.

Question!
?
11/12/2023

You might also like