2. 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#
4/13/2021 2
3. 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
4/13/2021 3
4. 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
C# code is compiled as managed code
Combines the best features of Visual Basic, C++ and Java
4/13/2021 4
5. C# Features
Simple
Modern
Object-Oriented
Type-safe
Versionable
Compatible
Secure
4/13/2021 5
6. 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
4/13/2021 6
7. 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.
4/13/2021 7
8. 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 Int16 0 -32768 32767
ushort 2 UInt16 0 0 65535
int 4 Int32 0 -2147483648 2147483647
uint 4 UInt32 0u 0 4294967295
long 8 Int64 0L -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
4/13/2021 8
10. 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
4/13/2021 10
11. 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 explicitextern false
finally fixed float for foreach goto
if implicitin 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 volatilewhile …
4/13/2021 11
12. 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
4/13/2021 12
13. 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
string message = greeting;
4/13/2021 13
14. 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;
4/13/2021 14
15. 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
4/13/2021 15
16. 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";
4/13/2021 16
17. Variables > Nullable Types
A nullable Type is a data type is that contain the defined data type or
the value of null.
are specific wrappers around the value types (as int, double and
bool) that allow storing data with a null value.
provides opportunity for types that generally do not allow lack of
value (i.e. value null)
to be used as reference types and to accept both normal values and the
special one null.
Any DataType can be declared nullable type with the help of operator "?".
Thus nullable types hold an optional value.
Wrapping a given type as nullable can be done in two ways:
nullabl <int> i1=null
int? i2 = i1;
4/13/2021 17
18. Variables > Nullable Types – Example
int? someInteger = null;
Console.WriteLine("This is the integer with Null value -> " + someInteger);
someInteger = 5;
Console.WriteLine( "This is the integer with value 5 -> " + someInteger);
double? someDouble = null;
Console.WriteLine("This is the real number with Null value -> " +
someDouble);
someDouble = 2.5;
Console.WriteLine("This is the real number with value 5 -> " +
someDouble);
4/13/2021 18
19. 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
4/13/2021 19
20. 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
4/13/2021 20
21. 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:WindowsNotepad.exe";
string verbatim = @"The is not escaped as .
I am at a new line.";
4/13/2021 21
22. 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
4/13/2021 22
23. 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;
4/13/2021 23
24. 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
4/13/2021 24
25. 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
> …
4/13/2021 25
26. Convert data type > Example
decimal salary = 2453.32m;
string salaryString = salary.ToString();
salary=Decimal.Parse(salaryString);
Decimal.TryParse(salaryString, out salary);
double cgpa = 3.85;
string studentCgpa = “CGPA: “+ cgpa; //automatic call to ToString method
string salesString = “$45268.25”;
decimal sales = 0m;
Decimal.TryParse(salesString, out sales); //sales is 0
string gradePoint = “63.25”;
string totalCredit = “22”;
double gpa = Convert.ToDouble(pgradePoint)/Convert.ToInt32(totalCredit);
4/13/2021 26
27. Convert data type > Formatted String
using methods to convert formatted strings
C or c – Currency
P or p – Percent
N or n – Number
F or f – Float
D or d – Digits
E or e – Exponential
G or g – General
Use
ToString method or
Format method
4/13/2021 27
28. Exrcise 1
declare and initialize the following types of data
int
float
double
string
decimal
you must use approprate naming convention.
4/13/2021 28
29. exrcise 2
using approprate data type initialize the lamp status
4/13/2021 29
31. Comments in C#
To include information about your code
Not readable by the compiler
Single line comment
//comment
Multiple line comment
/* --------------
---- multiline comment -------
--------------*/
4/13/2021 31
32. Exercise
1. Which of the ff 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. What is Nullable data type and its advantage? Give example.
5. Write the output of the ff code snippet
string exercise = @“Please Students answer this exercise .
Please participate actively.";
Console.WriteLine(exercise );
6. Give an example for implicit and explicit type casting.
4/13/2021 32
33. C# > Operators and Expressions
Performing Simple Calculations with C#
4/13/2021 33
34. 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
4/13/2021 34
35. 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
4/13/2021 35
38. Operators in C# > Operators Precedence
Parenthesis is operator always has highest precedence
Note: prefer using parentheses, even when it seems difficult to
do so
4/13/2021 38
Precedence Operators
Higher |
&&
||
?:, ??
Lowest
=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=,
|=
39. 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
4/13/2021 39
40. 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
4/13/2021 40
41. 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)
4/13/2021 41
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
43. Bitwise Operators
Bitwise operator ~ turns all 0 to 1 and all 1 to 0
Like ! for boolean expressions but bit by bit
The operators |, & and ^ behave like ||, && and ^ for boolean expressions but bit by bit
The << and >> move the bits (left or right)
Bitwise operators are used on integer numbers (byte, sbyte, int, uint, long, ulong)
Bitwise operators are applied bit by bit
Behavior of the operators|, & and ^:
4/13/2021 43
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
45. 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
4/13/2021 45
46. Assignment Operators
Assignment operators are used to assign a value to a variable ,
=, +=, -=, |=, ...
Assignment operators example:
int x = 6;
int y = 4;
Console.WriteLine(y *= 2); // 8
int z = y = 3; // y=3 and z=3
Console.WriteLine(z); // 3
Console.WriteLine(x |= 1); // 7 (0110 | 0001)
Console.WriteLine(x += 3); // 10
Console.WriteLine(x /= 2); // 5
4/13/2021 46
47. 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
4/13/2021 47
48. Other Operators …
Member access operator . is used to access object members
Square brackets [] are used with arrays, indexers and attributes
Parentheses ( ) are used to override the default operator precedence
Class cast operator (type) is used to cast one compatible type to another
Conditional operator ?: has the form
b?x:y
> if b is true then the result is x else the result is y
Null coalescing/joining operator ??
x=y??0;
> If y is null set x=0 else set x=y
The new operator is used to create new objects
The typeof operator returns System.Type object (the reflection of a type)
The is operator checks if an object is compatible with given type
4/13/2021 48
49. Other Operators > Example
Examples
int a = 6;
int b = 4;
Console.WriteLine(a > b ? "a>b" : "b>=a"); // a>b
Console.WriteLine((long) a); // 6
int c = b = 3; // b=3; followed by c=3;
Console.WriteLine(c); // 3
Console.WriteLine(a is int); // True
Console.WriteLine((a+b)/2); // 4
Console.WriteLine(typeof(int)); // System.Int32
int d = new int();
Console.WriteLine(d); // 0
4/13/2021 49
50. 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));
4/13/2021 50
51. 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);
4/13/2021 51
52. 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);
3. Write the output of the ff code fragment.
ushort a = 3;
ushort b = 5;
Console.WriteLine(a ^ ~b);
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= 𝜋𝑟2
).
4/13/2021 52
53. Console Input / Output
Reading and Writing to the Console
4/13/2021 53
54. 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
4/13/2021 54
55. 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)
4/13/2021 55
56. 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
4/13/2021 56
57. 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
4/13/2021 57
58. 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
4/13/2021 58
59. 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()
4/13/2021 59
60. 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);
4/13/2021 60
61. Console.ReadKey()
Waits until a combination of keys is pressed
Reads a single character from console or a combination of keys
Returns a result of type ConsoleKeyInfo
KeyChar – holds the entered character
Modifiers – holds the state of [Ctrl], [Alt], …
ConsoleKeyInfo key = Console.ReadKey();
Console.WriteLine();
Console.WriteLine("Character entered: " + key.KeyChar);
Console.WriteLine("Special keys: " + key.Modifiers);
4/13/2021 61
62. 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);
4/13/2021 62
63. 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
string invalid = "xxx1845";
int value = int.Parse(invalid); // FormatException
4/13/2021 63
64. 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);
}
4/13/2021 64
65. 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);
}
4/13/2021 65
66. 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);
4/13/2021 66
68. Conditional Statements
Implementing Control Logic in C#
if Statement
if-else Statement
nested if Statements
multiple if-else-if-else-…
switch-case Statement
4/13/2021 68
69. 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)
{
statements;
}
4/13/2021 69
true
condition
statement
false
70. 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);
}
4/13/2021 70
71. 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)
{
statement1;
}
else
{
statement2;
}
4/13/2021 71
condition
first
statement
true
second
statement
false
72. 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.");
}
4/13/2021 72
73. 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;
4/13/2021 73
74. 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.");
}
}
4/13/2021 74
75. 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 …
4/13/2021 75
76. 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;
}
4/13/2021 76
77. 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
4/13/2021 77
78. 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
4/13/2021 78
79. Multiple Labels – Example
You can use multiple labels to execute the same statement in more than one
case
switch (animal)
{
case "dog" :
Console.WriteLine("MAMMAL");
break;
case "crocodile" :
case "tortoise" :
case "snake" :
Console.WriteLine("REPTILE");
break;
default :
Console.WriteLine("There is no such animal!");
break;
}
4/13/2021 79
80. Looping / Iterations Statements
Execute Blocks of Code Multiple Times
4/13/2021 80
81. 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
4/13/2021 81
82. Using while(…) Loop
Repeating a Statement While Given Condition Holds
The simplest and most frequently used loop
while (condition)
{
statements;
}
The repeat condition
Returns a boolean result of true or false
Also called loop condition
4/13/2021 82
true
condition
statement
false
83. While Loop > Example
int counter = 0;
while (counter < 10)
{
Console.WriteLine("Number : {0}", counter);
counter++;
}
4/13/2021 83
84. 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);
4/13/2021 84
85. Do-While Loop
Another loop structure is:
do
{
statements;
}
while (condition);
The block of statements is repeated
While the boolean loop condition holds
The loop is executed at least once
4/13/2021 85
true
condition
statement
false
86. 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);
}
4/13/2021 86
87. 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
4/13/2021 87
88. 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;
}
4/13/2021 88
89. 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
4/13/2021 89
90. 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
4/13/2021 90
91. 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;
}
…
}
4/13/2021 91
92. 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();
}
4/13/2021 92
93. 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
4/13/2021 93
94. 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:
4/13/2021 94
95. 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);
4/13/2021 95
96. 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
4/13/2021 96
97. Date and string data types
Working with Date and string data types
4/13/2021 97
98. 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);
4/13/2021 98
99. 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());
4/13/2021 99
100. 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
4/13/2021 100
101. 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;
4/13/2021 101
102. 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
4/13/2021 102
103. 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(); //
4/13/2021 103
104. 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
4/13/2021 104
105. 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”;
}
4/13/2021 105
106. Dates and Times > Perform Operations on Dates and Times
Methods for performing operations on dates and times
4/13/2021 106
107. 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;
}
4/13/2021 107
108. Format dates and times
Use Format methods of the String class to format dates and
times
Standard DateTime formatting
4/13/2021 108
109. Format dates and times …
Custom DateTime formatting
4/13/2021 109
112. 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
4/13/2021 112
113. 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, …
4/13/2021 113
114. 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
4/13/2021 114
115. 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, 4);
4/13/2021 115
117. 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))
> {
> …
> }
4/13/2021 117
118. 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);
4/13/2021 118
119. 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
4/13/2021 119
121. 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
4/13/2021 121
122. 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);
4/13/2021 122
124. 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);
}
4/13/2021 124
125. 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 = " tnHello!!! n";
string clean = s.Trim(' ', ',' ,'!', 'n','t');
Console.WriteLine(clean); //
Using TrimStart() and TrimEnd()
string s = " C# ";
string clean = s.TrimStart(); // clean =
4/13/2021 125
126. 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
4/13/2021 126
127. Methods, events and delegates
Subroutines in Computer Programming
4/13/2021 127
128. 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
4/13/2021 128
129. 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
4/13/2021 129
130. 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;
}
4/13/2021 130
131. 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);
4/13/2021 131
132. Optional Parameters
C# 4.0 supports optional parameters with default values:
void PrintNumbers(int start=0; int end=100)
{
for (int i=start; i<=end; i++)
{
Console.Write("{0} ", i);
}
}
The above method can be called in several ways:
PrintNumbers(5, 10);
PrintNumbers(15);
PrintNumbers();
If you define an optional parameter, every parameters after that parameters must be defined
as optional
If you pass a value to an optional parameter by position, you must pass a value to all
parameters before that parameter
You can also pass value by name, code the parameter name followed by a colon followed by
the value/argument name
PrintNumbers(end: 40, start: 35);
4/13/2021 132
133. 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);
4/13/2021 133
134. 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);
}
4/13/2021 134
135. 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
4/13/2021 135
137. 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
4/13/2021 137
138. 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.
4/13/2021 138
139. Objects vs Class
An instance of a class is called an object.
Classes provide the structure for objects
Define their prototype, act as template
Classes define:
Set of attributes
> Represented by variables and properties
> Hold their state
Set of actions (behavior)
> Represented by methods
A class defines the methods and types of data associated with an
object
4/13/2021 139
Account
+Owner: Person
+Ammount: double
+Suspend()
+Deposit(sum:double)
+Withdraw(sum:double)
140. 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
4/13/2021 140
141. 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, …)
4/13/2021 141
142. 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
4/13/2021 142
143. 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
4/13/2021 143
144. 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!");
}
}
4/13/2021 144
145. 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)
4/13/2021 145
146. 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;
4/13/2021 146
147. 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
4/13/2021 147
148. 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
4/13/2021 148
149. 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 ...
}
4/13/2021 149
150. 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
4/13/2021 150
151. 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
4/13/2021 151
152. 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
4/13/2021 152
153. 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)
4/13/2021 153
154. 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>)
4/13/2021 154
155. 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.
4/13/2021 155
156. 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.
4/13/2021 156
157. 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.
4/13/2021 157
158. 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
4/13/2021 158
159. 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
4/13/2021 159
160. 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;
4/13/2021 160
161. 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
4/13/2021 161
162. 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>();
}
}
4/13/2021 162
163. 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
4/13/2021 163
165. Array
An array is a sequence of elements
All elements are of the same type
The order of the elements is fixed
Has fixed size (Array.Length)
Zero based index
Is reference type
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
4/13/2021 165
C# Array Types
There are 3 types of arrays in C# programming:
Single Dimensional Array
Multidimensional Array
Jagged Array
166. 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"
};
4/13/2021 166
167. 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
4/13/2021 167
168. 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]);
}
4/13/2021 168
169. 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);
}
4/13/2021 169
170. 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)
4/13/2021 170
171. 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);
}
}
4/13/2021 171
172. 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();
}
4/13/2021 172
173. 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;
}
4/13/2021 173
174. 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
4/13/2021 174
175. 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];
4/13/2021 175
176. 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
4/13/2021 176
177. 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
4/13/2021 177
178. 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
4/13/2021 178
179. 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);
4/13/2021 179
180. 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.
4/13/2021 180
181. ArrayList > Example
ArrayList al = new ArrayList();
Console.WriteLine("Adding some numbers:");
al.Add(45);
al.Add(78);
al.Add(33);
al.Add(56);
al.Add(12);
al.Add(23);
al.Add(9);
Console.WriteLine("Capacity: {0} ", al.Capacity);
Console.WriteLine("Count: {0}", al.Count);
Console.Write("Content: ");
foreach (int i in al)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.Write("Sorted Content: ");
al.Sort();
foreach (int i in al)
{
Console.Write(i + " ");
}
Console.WriteLine();
ArrayList arrrayList = new ArrayList();
arrrayList.Add(“One”);
arrrayList.Add(2);
arrrayList.Add(“Three”);
arrrayList.Add(4);
int number = 0;
foreach(object obj in araayList)
{
If(obj is int)
{
number += (int) obj;
}
}
4/13/2021 181
182. 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);
4/13/2021 182
183. 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
4/13/2021 183
184. 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]);
}
4/13/2021 184
185. 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
4/13/2021 185
186. 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
4/13/2021 186
187. 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
4/13/2021 187
UsageMain usage of this nullable type is when we are passing any parameter to Stored Procedure or Database objects. If a column in a Table allows Null value , then in this case we should use Nullable type.For example, say I have a Stored Procedure which accepts two in parameter @A and @B. It gives me back one out Parameter @C.This output Parameter can be Null also. So in that case we should use a Nullable Variable which can take Null also as allowed values.So to conclude, Nullable Types allows us to declare variables in .net which can be used effectively while dealing with Database.
A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.
It is possible to mix jagged and multidimensional arrays. The following is a declaration and initialization of a single-dimensional jagged array that contains two-dimensional array elements of different sizes:
int[][,] jaggedArray = new int[4][,] { new int[,] { {11,23}, {58,78} }, new int[,] { {50,62}, {45,65}, {85,15} }, new int[,] { {245,365}, {385,135} }, new int[,] { {1,2}, {4,4}, {4,5} } }; We should be careful using methods like GetLowerBound(), GetUpperBound, GetLength, etc. with jagged arrays. Since jagged arrays are constructed out of single-dimensional arrays, they shouldn't be treated as having multiple dimensions in the same way that rectangular arrays do.
Practical demonstration of jagged array of integers
using System; namespace jagged_array { class Program { static void Main(string[] args) { // Declare the array of four elements: int[][] jaggedArray = new int[4][]; // Initialize the elements: jaggedArray[0] = new int[2] { 7, 9 }; jaggedArray[1] = new int[4] { 12, 42, 26, 38 }; jaggedArray[2] = new int[6] { 3, 5, 7, 9, 11, 13 }; jaggedArray[3] = new int[3] { 4, 6, 8 }; // Display the array elements: for (int i = 0; i < jaggedArray.Length; i++) { System.Console.Write("Element({0}): ", i + 1); for (int j = 0; j < jaggedArray[i].Length; j++) { System.Console.Write(jaggedArray[i][j] + "\t"); } System.Console.WriteLine(); } Console.ReadLine(); } } } Run the code to see the output.
Practical demonstration of jagged array of string
using System; namespace jagged_array { class Program { static void Main(string[] args) { string[][] Members = new string[4][]{ new string[]{"Rocky", "Sam", "Alex"}, new string[]{"Peter", "Sonia", "Prety", "Ronnie", "Dino"}, new string[]{"Yomi", "John", "Sandra", "Alex", "Tim", "Shaun"}, new string[]{"Teena", "Mathew", "Arnold", "Stallone", "Goddy", "Samson", "Linda"}, }; for (int i = 0; i < Members.Length; i++) { System.Console.Write("Name List ({0}): ", i + 1); for (int j = 0; j < Members[i].Length; j++) { System.Console.Write(Members[i][j] + "\t"); } System.Console.WriteLine(); } Console.ReadKey(); } } } Run the code to see the output.