CSharp Language Overview Part 1

Hossein Zahed
Hossein ZahedLead Software Engineer en Maersk
C# Language Overview
(Part I)
DataTypes, Operators, Expressions, Statements,
Console I/O, Loops, Arrays, Methods
Table of Contents
1. DataTypes
2. Operators
3. Expressions
4. Console I/O
5. Conditional Statements
6. Loops
7. Arrays
8. Methods
2
Primitive DataTypes
IntegerTypes
Integer types are:
sbyte (-128 to 127): signed 8-bit
byte (0 to 255): unsigned 8-bit
short (-32,768 to 32,767): signed 16-bit
ushort (0 to 65,535): unsigned 16-bit
int (-2,147,483,648 to 2,147,483,647): signed 32-bit
uint (0 to 4,294,967,295): unsigned 32-bit
4
IntegerTypes (2)
More integer types:
long (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807):
signed 64-bit
ulong (0 to 18,446,744,073,709,551,615): unsigned 64-bit
5
IntegerTypes – Example
Measuring time
Depending on the unit of measure we may use different data
types:
byte centuries = 20; // Usually a small number
ushort years = 2000;
uint days = 730480;
ulong hours = 17531520; // May be a very big number
Console.WriteLine("{0} centuries is {1} years, or {2}
days, or {3} hours.", centuries, years, days, hours);
6
Floating-Point Types
Floating-point types are:
float (±1.5 × 10−45 to ±3.4 × 1038): 32-bits, precision of 7 digits
double (±5.0 × 10−324 to ±1.7 × 10308): 64-bits, precision of 15-16
digits
The default value of floating-point types:
Is 0.0F for the float type
Is 0.0D for the double type
7
Fixed-PointTypes
There is a special fixed-point real number
type:
decimal (±1,0 × 10-28 to ±7,9 × 1028): 128-bits,
precision of 28-29 digits
Used for financial calculations with low loss of
precision
No round-off errors
The default value of decimal type is:
0.0M (M is the suffix for decimal numbers)
8
PI Precision – Example
See below the difference in precision when using float and
double:
NOTE:The “f” suffix in the first statement!
Real numbers are by default interpreted as double!
One should explicitly convert them to float
float floatPI = 3.141592653589793238f;
double doublePI = 3.141592653589793238;
Console.WriteLine("Float PI is: {0}", floatPI);
Console.WriteLine("Double PI is: {0}", doublePI);
9
Abnormalities in the
Floating-Point Calculations
Sometimes abnormalities can be observed
when using floating-point numbers
Comparing floating-point numbers can not be
done directly with the == operator
Example:
float a = 1.0f;
float b = 0.33f;
float sum = 1.33f;
bool equal = (a+b == sum); // False!!!
Console.WriteLine("a+b={0} sum={1} equal={2}",
a+b, sum, equal);
10
The Boolean DataType
The Boolean DataType:
Is declared by the bool keyword
Has two possible values: true and false
Is useful in logical expressions
The default value is false
11
BooleanValues – Example
Here we can see how boolean variables take values of true or
false:
int a = 1;
int b = 2;
bool greaterAB = (a > b);
Console.WriteLine(greaterAB); // False
bool equalA1 = (a == 1);
Console.WriteLine(equalA1); // True
12
The Character DataType
The Character DataType:
Represents symbolic information
Is declared by the char keyword
Gives each symbol a corresponding integer code
Has a '0' default value
Takes 16 bits of memory (from U+0000 to U+FFFF)
13
Characters and Codes
The example below shows that every symbol has an its unique
code:
char symbol = 'a';
Console.WriteLine("The code of '{0}' is: {1}",
symbol, (int) symbol);
symbol = 'b';
Console.WriteLine("The code of '{0}' is: {1}",
symbol, (int) symbol);
symbol = 'A';
Console.WriteLine("The code of '{0}' is: {1}",
symbol, (int) symbol);
14
The String DataType
The String DataType:
Represents a sequence of characters
Is declared by the string keyword
Has a default value null (no value)
Strings are enclosed in quotes:
Strings can be concatenated
string s = "Microsoft .NET Framework";
15
Saying Hello – Example
Concatenating the two names of a person to obtain his full
name:
NOTE: a space is missing between the two names!We have to
add it manually
string firstName = "Ivan";
string lastName = "Ivanov";
Console.WriteLine("Hello, {0}!", firstName);
string fullName = firstName + " " + lastName;
Console.WriteLine("Your full name is {0}.",
fullName);
16
The ObjectType
The object type:
Is declared by the object keyword
Is the “parent” of all other types
Can take any types of values according to the needs
17
Using Objects
Example of an object variable taking different types of data:
object dataContainer = 5;
Console.Write("The value of dataContainer is: ");
Console.WriteLine(dataContainer);
dataContainer = "Five";
Console.Write ("The value of dataContainer is: ");
Console.WriteLine(dataContainer);
18
Variables and Identifiers
DeclaringVariables
When declaring a variable we:
Specify its type
Specify its name (called identifier)
May give it an initial value
The syntax is the following:
Example:
<data_type> <identifier> [= <initialization>];
int height = 200;
20
Identifiers
Identifiers may consist of:
Letters (Unicode)
Digits [0-9]
Underscore "_"
Identifiers
Can begin only with a letter or an underscore
Cannot be a C# keyword
21
Identifiers (2)
Identifiers
Should have a descriptive name
It is recommended to use only Latin letters
Should be neither too long nor too short
Note:
In C# small letters are considered different than the capital letters
(case sensitivity)
22
Identifiers – Examples
Examples of correct identifiers:
Examples of incorrect identifiers:
int new; // new is a keyword
int 2Pac; // Cannot begin with a digit
int New = 2; // Here N is capital
int _2Pac; // This identifiers begins with _
string поздрав = "Hello"; // Unicode symbols used
// The following is more appropriate:
string greeting = "Hello";
int n = 100; // Undescriptive
int numberOfClients = 100; // Descriptive
// Overdescriptive identifier:
int numberOfPrivateClientOfTheFirm = 100;
23
Literals
Integer Literals
Examples of integer literals
The '0x' and '0X' prefixes mean a hexadecimal value, e.g.
0xA8F1
The 'u' and 'U' suffixes mean a ulong or uint type, e.g.
12345678U
The 'l' and 'L' suffixes mean a long or ulong type, e.g.
9876543L
25
Integer Literals – Example
Note: the letter ‘l’ is easily confused with the
digit ‘1’ so it’s better to use ‘L’!!!
// The following variables are
// initialized with the same value:
int numberInHex = -0x10;
int numberInDec = -16;
// The following causes an error,
because 234u is of type uint
int unsignedInt = 234u;
// The following causes an error,
because 234L is of type long
int longInt = 234L;
26
Real Literals
The real literals:
Are used for values of type float and double
May consist of digits, a sign and “.”
May be in exponential formatting
The “f” and “F” suffixes mean float
The “d” and “D” suffixes mean double
The default interpretation is double
27
Real Literals – Example
Example of incorrect float literal:
A correct way to assign floating-point value (using also the
exponential format):
// The following causes an error
// because 12.5 is double by default
float realNumber = 12.5;
// The following is the correct
// way of assigning the value:
float realNumber = 12.5f;
// This is the same value in exponential format:
realNumber = 1.25e+1f;
28
Character Literals
The character literals:
Are used for values of the char type
Consist of two single quotes surrounding the value: '<value>'
The value may be:
Symbol
The code of the symbol
Escaping sequence
29
Escaping Sequences
Escaping sequences are:
Means of presenting a symbol that is usually
interpreted otherwise (like ')
Means of presenting system symbols (like the
new line symbol)
Common escaping sequences are:
 ' for single quote
 " for double quote
  for backslash
 n for new line
30
Character Literals – Example
Examples of different character literals:
char symbol = 'a'; // An ordinary symbol
symbol = 'u0061'; // Unicode symbol code in
// a hexadecimal format
symbol = '''; // Assigning the single quote symbol
symbol = ''; // Assigning the backslash symbol
symbol = "a"; // Incorrect: use single quotes
31
String Literals
String literals:
Are used for values of the string
type
Consist of two double quotes
surrounding the value: "<value>"
May have a @ prefix which ignores
the used escaping sequences
The value is a sequence of
character literals
32
String Literals – Example
Benefits of quoted strings (the @ prefix):
In quoted strings " is used instead of ""!
// Here is a string literal using escape sequences
string quotation = ""Hello, Jude", he said.";
string path = "C:WINNTDartsDarts.exe";
// Here is an example of the usage of @
quotation = @"""Hello, Jimmy!"", she answered.";
path = @"C:WINNTDartsDarts.exe";
33
Operators in C#
Categories of Operators in C#
Category Operators
Arithmetic + - * / % ++ --
Logical && || ^ !
Binary & | ^ ~ << >>
Comparison == != < > <= >=
Assignment
= += -= *= /= %= &= |=
^= <<= >>=
String concatenation +
Type conversion is as typeof
Other . [] () ?: new
35
Operators Precedence
Precedence Operators
Highest ++ -- (postfix) new typeof
++ -- (prefix) + - (unary) ! ~
* / %
+ -
<< >>
< > <= >= is as
== !=
&
Lower ^
36
Operators Precedence (2)
Precedence Operators
Higher |
&&
||
?:
Lowest
= *= /= %= += -= <<= >>= &=
^= |=
Parenthesis operator always has highest
precedence
Note: prefer using parentheses, even when it
seems stupid to do so 37
Arithmetic Operators
Arithmetic operators +, -, * are the same as in math
Division operator / if used on integers returns integer (without
rounding)
Remainder operator % returns the remainder from division of
integers
The special addition operator ++ increments a variable
38
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
39
Logical Operators
Logical operators take boolean operands and return boolean
result
Operator ! turns true to false and false
to true
Behavior of the operators &&, || and ^
(1 == true, 0 == false) :
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
40
Logical Operators – Example
Using the logical operators:
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
41
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)
Behavior of the operators|, & and ^:
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
42
Bitwise Operators (2)
Bitwise operators are used on integer numbers (byte, sbyte,
int, uint, long, ulong)
Bitwise operators are applied bit by bit
Examples:
ushort a = 3; // 00000011
ushort b = 5; // 00000101
Console.WriteLine( a | b); // 00000111
Console.WriteLine( a & b); // 00000001
Console.WriteLine( a ^ b); // 00000110
Console.WriteLine(~a & b); // 00000100
Console.WriteLine( a<<1 ); // 00000110
Console.WriteLine( a>>1 ); // 00000001
43
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 == b); // False
Console.WriteLine(a == a); // True
Console.WriteLine(a != ++b); // False
44
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
Console.WriteLine(x += 3); // 10
Console.WriteLine(x /= 2); // 5
45
Other Operators
String concatenation operator + is used to concatenate strings
If the second operand is not a string, it is converted to string
automatically
string first = "First";
string second = "Second";
Console.WriteLine(first + second);
// FirstSecond
string output = "The number is : ";
int number = 5;
Console.WriteLine(output + number);
// The number is : 5
46
Other Operators (2)
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
47
Other Operators (3)
Conditional operator ?: has the form
(if b is true then the result is x else the result is 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
b ? x : y
48
Other Operators – Example
Using some other operators:
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
49
Type Conversions
Example of implicit and explicit conversions:
Note: explicit conversion may be used even if not required by
the compiler
float heightInMeters = 1.74f; // Explicit conversion
double maxHeight = heightInMeters; // Implicit
double minHeight = (double) heightInMeters; // Explicit
float actualHeight = (float) maxHeight; // Explicit
float maxHeightFloat = maxHeight; // Compilation error!
50
Expressions
Expressions
Expressions are sequences of operators, literals and variables
that are evaluated to some value
Examples:
int r = (150-20) / 2 + 5;
// Expression for calculation of circle area
double surface = Math.PI * r * r;
// Expression for calculation of circle perimeter
double perimeter = 2 * Math.PI * r;
52
Using to the Console
Printing / Reading Strings and Numbers
The Console Class
Provides methods for input and output
Input
 Read(…) – reads a single character
 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
54
Console.Write(…)
Printing more than one variable using a
formatting string
int a = 15;
...
Console.Write(a); // 15
Printing an integer variable
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
55
Console.WriteLine(…)
Printing more than one variable using a
formatting string
string str = "Hello C#!";
...
Console.WriteLine(str);
Printing a string variable
string name = "Marry";
int year = 1987;
...
Console.Write("{0} was born in {1}.", name, year);
// Marry was born in 1987.
Next printing will start from the next line
56
Printing to the Console – Example
static void Main()
{
string name = "Peter";
int age = 18;
string town = "Sofia";
Console.Write("{0} is {1} years old from {2}.",
name, age, town);
// Result: Peter is 18 years old from Sofia.
Console.Write("This is on the same line!");
Console.WriteLine("Next sentence will be" +
" on a new line.");
Console.WriteLine("Bye, bye, {0} from {1}.",
name, town);
}
57
Reading from the Console
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()
58
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);
59
Reading NumeralTypes
Numeral types can not be read directly from the
console
To read a numeral type do 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);
60
Reading NumeralTypes (2)
Another way to parse string to numeral
type is to use int.TryParse(…) method
Sets default value for the type if the parse fails
Returns bool
 True if the parse is successfull
 False if it fails
int a;
string line = Console.ReadLine();
int.TryParse(line, out a);
The result from the parse will be assigned to
the variable parseResult
61
Converting Strings to Numbers
Numeral types have a method Parse(…) for
extracting the numeral value from a string
 int.Parse(string) – string  int
 long.Parse(string) – string  long
 float.Parse(string) – string  float
 Causes FormatException in case of error
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
62
Conditional Statements
Implementing Conditional Logic
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;
}
64
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);
}
65
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 (expression)
{
statement1;
}
else
{
statement2;
}
66
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.");
}
67
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;
68
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.");
}
}
69
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;
}
70
Loops
Repeating Statements MultipleTimes
HowTo Use While Loop?
The simplest and most frequently used loop
The repeat condition
Returns a boolean result of true or false
Also called loop condition
while (condition)
{
statements;
}
72
While Loop – Example
int counter = 0;
while (counter < 10)
{
Console.WriteLine("Number : {0}", counter);
counter++;
}
73
Using Do-While Loop
Another loop structure is:
The block of statements is repeated
While the boolean loop condition holds
The loop is executed at least once
do
{
statements;
}
while (condition);
74
Factorial – 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);
}
75
For Loops
The typical for loop syntax is:
Consists of
Initialization statement
Boolean test expression
Update statement
Loop body block
for (initialization; test; update)
{
statements;
}
76
N^M – Example
Calculating n to power m (denoted as n^m):
static void Main()
{
int n = int.Parse(Console.ReadLine());
int m = int.Parse(Console.ReadLine());
decimal result = 1;
for (int i=0; i<m; i++)
{
result *= n;
}
Console.WriteLine("n^m = " + result);
}
77
For-Each Loops
The typical foreach loop syntax is:
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
foreach (Type element in collection)
{
statements;
}
78
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
79
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;
}
…
}
80
Nested Loops – Examples
Print all combinations fromTOTO 6/49
static void Main()
{
int i1, i2, i3, i4, i5, i6;
for (i1 = 1; i1 <= 44; i1++)
for (i2 = i1 + 1; i2 <= 45; i2++)
for (i3 = i2 + 1; i3 <= 46; i3++)
for (i4 = i3 + 1; i4 <= 47; i4++)
for (i5 = i4 + 1; i5 <= 48; i5++)
for (i6 = i5 + 1; i6 <= 49; i6++)
Console.WriteLine("{0} {1} {2} {3} {4} {5}",
i1, i2, i3, i4, i5, i6);
}
Warning:
execution of this
code could take
too long time.
81
Arrays
What are Arrays?
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)
0 1 2 3 4Array of 5
elements
Element
index
Element
of an array
… … … … …
83
Declaring Arrays
Declaration defines the type of the elements
Square brackets [] mean "array"
Examples:
Declaring array of integers:
Declaring array of strings:
int[] myIntArray;
string[] myStringArray;
84
Creating Arrays
Use the operator new
Specify array length
Example creating (allocating) array of 5 integers:
myIntArray = new int[5];
myIntArray
managed heap
(dynamic memory)
0 1 2 3 4
… … … … …
85
Creating and Initializing Arrays
Creating and initializing can be done together:
The new operator is not required when using curly brackets
initialization
myIntArray = {1, 2, 3, 4, 5};
myIntArray
managed heap
(dynamic memory)
0 1 2 3 4
… … … … …
86
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"
};
87
How to Access Array Element?
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
88
Reversing an Array – Example
Reversing the contents of an array
int[] array = new int[] {1, 2, 3, 4, 5};
// Get array size
int length = array.Length;
// Declare and create the reversed array
int[] reversed = new int[length];
// Initialize the reversed array
for (int index = 0; index < length; index++)
{
reversed[length-index-1] = array[index];
}
89
Processing Arrays: foreach
How foreach loop works?
type – the type of the element
value – local name of variable
array – processing array
Used when no indexing is needed
All elements are accessed one by one
Elements can not be modified (read only)
foreach (type value in array)
90
Processing Arrays Using
foreach – Example
Print all elements of a string[] array:
string[] capitals =
{
"Sofia",
"Washington",
"London",
"Paris"
};
foreach (string capital in capitals)
{
Console.WriteLine(capital);
}
91
Multidimensional Arrays
Multidimensional arrays have more than one dimension (2, 3,
…)
The most important multidimensional arrays are the 2-
dimensional
 Known as matrices or tables
Example of matrix of integers with 2 rows and 4 columns:
5 0 -2 4
5 6 7 8
0 1 2 3
0
1
92
Declaring and Creating Multidimensional
Arrays
Declaring multidimensional arrays:
Creating a multidimensional array
Use new keyword
Must specify the size of each dimension
int[,] intMatrix;
float[,] floatMatrix;
string[,,] strCube;
int[,] intMatrix = new int[3, 4];
float[,] floatMatrix = new float[8, 2];
string[,,] stringCube = new string[5, 5, 5];
93
Creating and Initializing Multidimensional
Arrays
Creating and initializing with values
multidimensional array:
Matrices are represented by a list of rows
 Rows consist of list of values
The first dimension comes first, the second
comes next (inside the first)
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)
94
Reading Matrix – 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];
for (int row=0; row<rows; row++)
{
for (int col=0; col<cols; col++)
{
Console.Write("matrix[{0},{1}] = ",
row, col);
matrix[row, col] =
int.Parse(Console.ReadLine());
}
}
95
Printing Matrix – 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();
}
96
Strings andText Processing
What Is String?
Strings are sequences of characters
Each character is a Unicode symbol
Represented by the string data type in C# (System.String)
Example:
string s = "Hello, C#";
H e l l o , C #s
98
The System.String Class
Strings are represented by System.String objects in .NET
Framework
String objects contain an immutable (read-only) sequence of
characters
Strings use Unicode in to support multiple languages and
alphabets
Strings are stored in the dynamic memory (managed heap)
System.String is reference type
99
The System.String Class (2)
String objects are like arrays of characters (char[])
Have fixed length (String.Length)
Elements can be accessed directly by index
 The index is in the range [0...Length-1]
string s = "Hello!";
int len = s.Length; // len = 6
char ch = s[1]; // ch = 'e'
0 1 2 3 4 5
H e l l o !
index =
s[index] =
100
Strings – Example
static void Main()
{
string s =
"Stand up, stand up, Balkan Superman.";
Console.WriteLine("s = "{0}"", s);
Console.WriteLine("s.Length = {0}", s.Length);
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine("s[{0}] = {1}", i, s[i]);
}
}
101
Declaring Strings
There are two ways of declaring string variables:
Using the C# keyword string
Using the .NET's fully qualified class name System.String
The above three declarations are equivalent
string str1;
System.String str2;
String str3;
102
Creating Strings
Before initializing a string variable has null value
Strings can be initialized by:
Assigning a string literal to the string variable
Assigning the value of another string variable
Assigning the result of operation of type string
103
Creating Strings (2)
Not initialized variables has value of null
Assigning a string literal
Assigning from another string variable
Assigning from the result of string operation
string s; // s is equal to null
string s = "I am a string literal!";
string s2 = s;
string s = 42.ToString();
104
Reading and Printing Strings
Reading strings from the console
Use the method Console.ReadLine()
string s = Console.ReadLine();
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
Console.Write("Hello, {0}! ", name);
Console.WriteLine("Welcome to our party!");
Printing strings to the console
Use the methods Write() and WriteLine()
105
A number of ways exist to compare two strings:
Dictionary-based string comparison
 Case-insensitive
 Case-sensitive
Comparing Strings
int result = string.Compare(str1, str2, true);
// result == 0 if str1 equals str2
// result < 0 if str1 if before str2
// result > 0 if str1 if after str2
string.Compare(str1, str2, false);
106
Comparing Strings – Example
Finding the first string in a lexicographical order from a given list of
strings:
string[] towns = {"Sofia", "Varna", "Plovdiv",
"Pleven", "Bourgas", "Rousse", "Yambol"};
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);
107
Concatenating Strings
There are two ways to combine strings:
 Using the Concat() method
 Using the + or the += operators
Any object can be appended to string
string str = String.Concat(str1, str2);
string str = str1 + str2 + str3;
string str += str1;
string name = "Peter";
int age = 22;
string s = name + " " + age; //  "Peter 22"
108
Searching in Strings
Finding a character or substring within given
string
 First occurrence
 First occurrence starting at given position
 Last occurrence
IndexOf(string str)
IndexOf(string str, int startIndex)
LastIndexOf(string)
109
Searching in Strings – Example
string str = "C# Programming Course";
int index = str.IndexOf("C#"); // index = 0
index = str.IndexOf("Course"); // index = 15
index = str.IndexOf("COURSE"); // index = -1
// IndexOf is case-sensetive. -1 means not found
index = str.IndexOf("ram"); // index = 7
index = str.IndexOf("r"); // index = 4
index = str.IndexOf("r", 5); // index = 7
index = str.IndexOf("r", 8); // index = 18
0 1 2 3 4 5 6 7 8 9 10 11 12 13 …
C # P r o g r a m m i n g …
index =
s[index] =
110
Extracting Substrings
Extracting substrings
 str.Substring(int startIndex, int length)
 str.Substring(int startIndex)
string filename = @"C:PicsRila2009.jpg";
string name = filename.Substring(8, 8);
// name is Rila2009
string filename = @"C:PicsSummer2009.jpg";
string nameAndExtension = filename.Substring(8);
// nameAndExtension is Summer2009.jpg
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
C :  P i c s  R i l a 2 0 0 5 . j p g
111
Splitting Strings
To split a string by given separator(s) use the following method:
Example: string[] Split(params char[])
string listOfBeers =
"Amstel, Zagorka, Tuborg, Becks.";
string[] beers =
listOfBeers.Split(' ', ',', '.');
Console.WriteLine("Available beers are:");
foreach (string beer in beers)
{
Console.WriteLine(beer);
}
112
Replacing and Deleting Substrings
Replace(string, string) – replaces all occurrences of given string
with another
 The result is new string (strings are immutable)
Remove(index, length) – deletes part of a string and produces new
string as result
string cocktail = "Vodka + Martini + Cherry";
string replaced = cocktail.Replace("+", "and");
// Vodka and Martini and Cherry
string price = "$ 1234567";
string lowPrice = price.Remove(2, 3);
// $ 4567
113
Changing Character Casing
Using method ToLower()
Using method ToUpper()
string alpha = "aBcDeFg";
string lowerAlpha = alpha.ToLower(); // abcdefg
Console.WriteLine(lowerAlpha);
string alpha = "aBcDeFg";
string upperAlpha = alpha.ToUpper(); // ABCDEFG
Console.WriteLine(upperAlpha);
114
Trimming White Space
Using method Trim()
Using method Trim(chars)
Using TrimStart() and TrimEnd()
string s = " example of white space ";
string clean = s.Trim();
Console.WriteLine(clean);
string s = " tnHello!!! n";
string clean = s.Trim(' ', ',' ,'!', 'n','t');
Console.WriteLine(clean); // Hello
string s = " C# ";
string clean = s.TrimStart(); // clean = "C# "
115
Constructing Strings
Strings are immutable
Concat(), Replace(), Trim(), ... return new
string, do not modify the old one
Do not use "+" for strings in a loop!
It runs very, very inefficiently!
public static string DupChar(char ch, int count)
{
string result = "";
for (int i=0; i<count; i++)
result += ch;
return result;
}
Very bad practice.
Avoid this!
116
Changing the Contents of a String
– StringBuilder
Use the System.Text.StringBuilder class for
modifiable strings of characters:
Use StringBuilder if you need to keep adding
characters to a string
public static string ReverseString(string s)
{
StringBuilder sb = new StringBuilder();
for (int i = s.Length-1; i >= 0; i--)
sb.Append(s[i]);
return sb.ToString();
}
117
StringBuilder keeps a buffer memory,
allocated in advance
Most operations use the buffer memory and
do not allocate new objects
The StringBuilder Class
H e l l o , C # !StringBuilder:
Length=9
Capacity=15
Capacity
used buffer
(Length)
unused
buffer
118
StringBuilder – Example
Extracting all capital letters from a string
public static string ExtractCapitals(string s)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i<s.Length; i++)
{
if (Char.IsUpper(s[i]))
{
result.Append(s[i]);
}
}
return result.ToString();
}
119
Method ToString()
All classes have public virtual method ToString()
Returns a human-readable, culture-sensitive string representing
the object
Most .NET Framework types have own implementation of
ToString()
 int, float, bool, DateTime
int number = 5;
string s = "The number is " + number.ToString();
Console.WriteLine(s); // The number is 5
120
Method ToString(format)
We can apply specific formatting when converting objects to
string
 ToString(formatString) method
int number = 42;
string s = number.ToString("D5"); // 00042
s = number.ToString("X"); // 2A
// Consider the default culture is Bulgarian
s = number.ToString("C"); // 42,00 лв
double d = 0.375;
s = d.ToString("P2"); // 37,50 %
121
Formatting Strings
The formatting strings are different for the different types
Some formatting strings for numbers:
 D – number (for integer types)
 C – currency (according to current culture)
 E – number in exponential notation
 P – percentage
 X – hexadecimal number
 F – fixed point (for real numbers)
122
Method String.Format()
Applies templates for formatting strings
Placeholders are used for dynamic text
Like Console.WriteLine(…)
string template = "If I were {0}, I would {1}.";
string sentence1 = String.Format(
template, "developer", "know C#");
Console.WriteLine(sentence1);
// If I were developer, I would know C#.
string sentence2 = String.Format(
template, "elephant", "weigh 4500 kg");
Console.WriteLine(sentence2);
// If I were elephant, I would weigh 4500 kg.
123
Composite Formatting
The placeholders in the composite formatting strings are specified
as follows:
Examples:
{index[,alignment][:formatString]}
double d = 0.375;
s = String.Format("{0,10:F5}", d);
// s = " 0,37500"
int number = 42;
Console.WriteLine("Dec {0:D} = Hex {1:X}",
number, number);
// Dec 42 = Hex 2A
124
Formatting Dates
Dates have their own formatting strings
d, dd – day (with/without leading zero)
M, MM – month
yy, yyyy – year (2 or 4 digits)
h, HH, m, mm, s, ss – hour, minute, second
DateTime now = DateTime.Now;
Console.WriteLine(
"Now is {0:d.MM.yyyy HH:mm:ss}", now);
// Now is 31.11.2009 11:30:32
125
форум програмиране,форум уеб дизайн
курсове и уроци по програмиране,уеб дизайн – безплатно
програмиранеза деца – безплатни курсове и уроци
безплатен SEO курс -оптимизация за търсачки
уроци по уеб дизайн, HTML,CSS, JavaScript,Photoshop
уроци по програмиранеи уеб дизайн за ученици
ASP.NET MVCкурс – HTML,SQL,C#,.NET,ASP.NETMVC
безплатен курс"Разработка на софтуер в cloud среда"
BG Coder -онлайн състезателна система -online judge
курсове и уроци по програмиране,книги – безплатно отНаков
безплатен курс"Качествен програменкод"
алго академия – състезателно програмиране,състезания
ASP.NET курс -уеб програмиране,бази данни, C#,.NET,ASP.NET
курсове и уроци по програмиране– Телерик академия
курсмобилни приложения сiPhone, Android,WP7,PhoneGap
freeC#book, безплатна книга C#,книга Java,книга C#
Дончо Минков -сайт за програмиране
Николай Костов -блог за програмиране
C#курс,програмиране,безплатно
C# Language Overview (Part I)
1 de 126

Recomendados

C# overview part 1 por
C# overview part 1C# overview part 1
C# overview part 1sagaroceanic11
1.5K vistas108 diapositivas
Data type in c por
Data type in cData type in c
Data type in cthirumalaikumar3
3.4K vistas20 diapositivas
Getting started with c++ por
Getting started with c++Getting started with c++
Getting started with c++Bussines man badhrinadh
447 vistas35 diapositivas
C sharp part 001 por
C sharp part 001C sharp part 001
C sharp part 001Ralph Weber
746 vistas110 diapositivas
Basics of c++ por
Basics of c++Basics of c++
Basics of c++Madhavendra Dutt
1.4K vistas56 diapositivas
C++ Programming Language Training in Ambala ! Batra Computer Centre por
C++ Programming Language Training in Ambala ! Batra Computer CentreC++ Programming Language Training in Ambala ! Batra Computer Centre
C++ Programming Language Training in Ambala ! Batra Computer Centrejatin batra
180 vistas17 diapositivas

Más contenido relacionado

La actualidad más candente

C++ Tokens por
C++ TokensC++ Tokens
C++ TokensAmrit Kaur
6.5K vistas10 diapositivas
C++ Basics por
C++ BasicsC++ Basics
C++ BasicsHimanshu Sharma
563 vistas46 diapositivas
Keywords, identifiers ,datatypes in C++ por
Keywords, identifiers ,datatypes in C++Keywords, identifiers ,datatypes in C++
Keywords, identifiers ,datatypes in C++Ankur Pandey
359 vistas34 diapositivas
Fundamentals of c programming por
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programmingChitrank Dixit
3.1K vistas6 diapositivas
02a fundamental c++ types, arithmetic por
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic Manzoor ALam
1.3K vistas38 diapositivas
C++ por
C++C++
C++Shyam Khant
1.5K vistas24 diapositivas

La actualidad más candente(20)

C++ Tokens por Amrit Kaur
C++ TokensC++ Tokens
C++ Tokens
Amrit Kaur6.5K vistas
Keywords, identifiers ,datatypes in C++ por Ankur Pandey
Keywords, identifiers ,datatypes in C++Keywords, identifiers ,datatypes in C++
Keywords, identifiers ,datatypes in C++
Ankur Pandey359 vistas
Fundamentals of c programming por Chitrank Dixit
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programming
Chitrank Dixit3.1K vistas
02a fundamental c++ types, arithmetic por Manzoor ALam
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
Manzoor ALam1.3K vistas
Learn c++ Programming Language por Steve Johnson
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
Steve Johnson1.2K vistas
Variables and data types in C++ por Ameer Khan
Variables and data types in C++Variables and data types in C++
Variables and data types in C++
Ameer Khan1.8K vistas
pointer, structure ,union and intro to file handling por Rai University
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University997 vistas
(2) cpp imperative programming por Nico Ludwig
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programming
Nico Ludwig560 vistas
Basic of c &c++ por guptkashish
Basic of c &c++Basic of c &c++
Basic of c &c++
guptkashish895 vistas
Getting started with c++ por K Durga Prasad
Getting started with c++Getting started with c++
Getting started with c++
K Durga Prasad7.5K vistas
constants, variables and datatypes in C por Sahithi Naraparaju
constants, variables and datatypes in Cconstants, variables and datatypes in C
constants, variables and datatypes in C
Sahithi Naraparaju14.6K vistas

Destacado

Web II - 02 - How ASP.NET Works por
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksRandy Connolly
10.4K vistas98 diapositivas
Entity Framework Overview por
Entity Framework OverviewEntity Framework Overview
Entity Framework Overviewukdpe
2.7K vistas23 diapositivas
HTML & XHTML Basics por
HTML & XHTML BasicsHTML & XHTML Basics
HTML & XHTML BasicsHossein Zahed
3.1K vistas37 diapositivas
CSS Basics por
CSS BasicsCSS Basics
CSS BasicsHossein Zahed
1.4K vistas10 diapositivas
ASP.NET 02 - How ASP.NET Works por
ASP.NET 02 - How ASP.NET WorksASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET WorksRandy Connolly
15.8K vistas34 diapositivas
ASP.NET MVC 5 - EF 6 - VS2015 por
ASP.NET MVC 5 - EF 6 - VS2015ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015Hossein Zahed
3.4K vistas148 diapositivas

Destacado(10)

Web II - 02 - How ASP.NET Works por Randy Connolly
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET Works
Randy Connolly10.4K vistas
Entity Framework Overview por ukdpe
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
ukdpe2.7K vistas
ASP.NET 02 - How ASP.NET Works por Randy Connolly
ASP.NET 02 - How ASP.NET WorksASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET Works
Randy Connolly15.8K vistas
ASP.NET MVC 5 - EF 6 - VS2015 por Hossein Zahed
ASP.NET MVC 5 - EF 6 - VS2015ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015
Hossein Zahed3.4K vistas
ASP.NET 12 - State Management por Randy Connolly
ASP.NET 12 - State ManagementASP.NET 12 - State Management
ASP.NET 12 - State Management
Randy Connolly3.3K vistas
Microsoft SQL Server 2008 por Hossein Zahed
Microsoft SQL Server 2008Microsoft SQL Server 2008
Microsoft SQL Server 2008
Hossein Zahed1.6K vistas

Similar a CSharp Language Overview Part 1

02. Primitive Data Types and Variables por
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and VariablesIntro C# Book
38.2K vistas69 diapositivas
02 Primitive data types and variables por
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variablesmaznabili
560 vistas71 diapositivas
Java: Primitive Data Types por
Java: Primitive Data TypesJava: Primitive Data Types
Java: Primitive Data TypesTareq Hasan
3.8K vistas114 diapositivas
Csharp4 basics por
Csharp4 basicsCsharp4 basics
Csharp4 basicsAbed Bukhari
1.7K vistas66 diapositivas
03 and 04 .Operators, Expressions, working with the console and conditional s... por
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
14.4K vistas60 diapositivas
presentation_data_types_and_operators_1513499834_241350.pptx por
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxKrishanPalSingh39
4 vistas52 diapositivas

Similar a CSharp Language Overview Part 1(20)

02. Primitive Data Types and Variables por Intro C# Book
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
Intro C# Book38.2K vistas
02 Primitive data types and variables por maznabili
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variables
maznabili560 vistas
Java: Primitive Data Types por Tareq Hasan
Java: Primitive Data TypesJava: Primitive Data Types
Java: Primitive Data Types
Tareq Hasan3.8K vistas
03 and 04 .Operators, Expressions, working with the console and conditional s... por Intro C# Book
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book14.4K vistas
presentation_data_types_and_operators_1513499834_241350.pptx por KrishanPalSingh39
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
Literals, primitive datatypes, variables, expressions, identifiers por Tanishq Soni
Literals, primitive datatypes, variables, expressions, identifiersLiterals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiers
Tanishq Soni193 vistas
Csharp4 operators and_casts por Abed Bukhari
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
Abed Bukhari945 vistas
CSharpCheatSheetV1.pdf por ssusera0bb35
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdf
ssusera0bb3537 vistas
PROGRAMMING IN C - Inroduction.pptx por Nithya K
PROGRAMMING IN C - Inroduction.pptxPROGRAMMING IN C - Inroduction.pptx
PROGRAMMING IN C - Inroduction.pptx
Nithya K20 vistas
DISE - Windows Based Application Development in C# por Rasan Samarasinghe
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
Rasan Samarasinghe692 vistas

Más de Hossein Zahed

Machine Learning with ML.NET por
Machine Learning with ML.NETMachine Learning with ML.NET
Machine Learning with ML.NETHossein Zahed
14 vistas9 diapositivas
8 Database Paradigms por
8 Database Paradigms8 Database Paradigms
8 Database ParadigmsHossein Zahed
95 vistas10 diapositivas
مبانی رایانش ابری por
مبانی رایانش ابریمبانی رایانش ابری
مبانی رایانش ابریHossein Zahed
43 vistas9 diapositivas
HTTPS نحوه کارکرد پروتکل por
HTTPS نحوه کارکرد پروتکلHTTPS نحوه کارکرد پروتکل
HTTPS نحوه کارکرد پروتکلHossein Zahed
16 vistas17 diapositivas
مبانی چابکی و اسکرام por
مبانی چابکی و اسکراممبانی چابکی و اسکرام
مبانی چابکی و اسکرامHossein Zahed
13 vistas8 diapositivas
آموزش سی شارپ - بخش 1 por
آموزش سی شارپ - بخش 1آموزش سی شارپ - بخش 1
آموزش سی شارپ - بخش 1Hossein Zahed
11 vistas11 diapositivas

Más de Hossein Zahed(13)

Machine Learning with ML.NET por Hossein Zahed
Machine Learning with ML.NETMachine Learning with ML.NET
Machine Learning with ML.NET
Hossein Zahed14 vistas
مبانی رایانش ابری por Hossein Zahed
مبانی رایانش ابریمبانی رایانش ابری
مبانی رایانش ابری
Hossein Zahed43 vistas
HTTPS نحوه کارکرد پروتکل por Hossein Zahed
HTTPS نحوه کارکرد پروتکلHTTPS نحوه کارکرد پروتکل
HTTPS نحوه کارکرد پروتکل
Hossein Zahed16 vistas
مبانی چابکی و اسکرام por Hossein Zahed
مبانی چابکی و اسکراممبانی چابکی و اسکرام
مبانی چابکی و اسکرام
Hossein Zahed13 vistas
آموزش سی شارپ - بخش 1 por Hossein Zahed
آموزش سی شارپ - بخش 1آموزش سی شارپ - بخش 1
آموزش سی شارپ - بخش 1
Hossein Zahed11 vistas
فرآیند توسعه نرم افزار por Hossein Zahed
فرآیند توسعه نرم افزارفرآیند توسعه نرم افزار
فرآیند توسعه نرم افزار
Hossein Zahed17 vistas
تخته سیاه آنلاین por Hossein Zahed
تخته سیاه آنلاینتخته سیاه آنلاین
تخته سیاه آنلاین
Hossein Zahed10 vistas
مفاهیم اساسی برنامه نویسی کامپیوتر por Hossein Zahed
مفاهیم اساسی برنامه نویسی کامپیوترمفاهیم اساسی برنامه نویسی کامپیوتر
مفاهیم اساسی برنامه نویسی کامپیوتر
Hossein Zahed29 vistas
Network Essentials v2.0 por Hossein Zahed
Network Essentials v2.0Network Essentials v2.0
Network Essentials v2.0
Hossein Zahed2.4K vistas

Último

JioEngage_Presentation.pptx por
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptxadmin125455
6 vistas4 diapositivas
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports por
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug ReportsBushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug ReportsRa'Fat Al-Msie'deen
8 vistas49 diapositivas
Introduction to Maven por
Introduction to MavenIntroduction to Maven
Introduction to MavenJohn Valentino
6 vistas10 diapositivas
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra... por
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra....NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...Marc Müller
41 vistas62 diapositivas
predicting-m3-devopsconMunich-2023-v2.pptx por
predicting-m3-devopsconMunich-2023-v2.pptxpredicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptxTier1 app
9 vistas33 diapositivas
What is API por
What is APIWhat is API
What is APIartembondar5
10 vistas15 diapositivas

Último(20)

JioEngage_Presentation.pptx por admin125455
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptx
admin1254556 vistas
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports por Ra'Fat Al-Msie'deen
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug ReportsBushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra... por Marc Müller
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra....NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
Marc Müller41 vistas
predicting-m3-devopsconMunich-2023-v2.pptx por Tier1 app
predicting-m3-devopsconMunich-2023-v2.pptxpredicting-m3-devopsconMunich-2023-v2.pptx
predicting-m3-devopsconMunich-2023-v2.pptx
Tier1 app9 vistas
Dapr Unleashed: Accelerating Microservice Development por Miroslav Janeski
Dapr Unleashed: Accelerating Microservice DevelopmentDapr Unleashed: Accelerating Microservice Development
Dapr Unleashed: Accelerating Microservice Development
Miroslav Janeski12 vistas
predicting-m3-devopsconMunich-2023.pptx por Tier1 app
predicting-m3-devopsconMunich-2023.pptxpredicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptx
Tier1 app7 vistas
Myths and Facts About Hospice Care: Busting Common Misconceptions por Care Coordinations
Myths and Facts About Hospice Care: Busting Common MisconceptionsMyths and Facts About Hospice Care: Busting Common Misconceptions
Myths and Facts About Hospice Care: Busting Common Misconceptions
Understanding HTML terminology por artembondar5
Understanding HTML terminologyUnderstanding HTML terminology
Understanding HTML terminology
artembondar56 vistas
Quality Engineer: A Day in the Life por John Valentino
Quality Engineer: A Day in the LifeQuality Engineer: A Day in the Life
Quality Engineer: A Day in the Life
John Valentino7 vistas
AI and Ml presentation .pptx por FayazAli87
AI and Ml presentation .pptxAI and Ml presentation .pptx
AI and Ml presentation .pptx
FayazAli8713 vistas
Introduction to Git Source Control por John Valentino
Introduction to Git Source ControlIntroduction to Git Source Control
Introduction to Git Source Control
John Valentino6 vistas
360 graden fabriek por info33492
360 graden fabriek360 graden fabriek
360 graden fabriek
info33492143 vistas
DRYiCE™ iAutomate: AI-enhanced Intelligent Runbook Automation por HCLSoftware
DRYiCE™ iAutomate: AI-enhanced Intelligent Runbook AutomationDRYiCE™ iAutomate: AI-enhanced Intelligent Runbook Automation
DRYiCE™ iAutomate: AI-enhanced Intelligent Runbook Automation
HCLSoftware6 vistas

CSharp Language Overview Part 1

  • 1. C# Language Overview (Part I) DataTypes, Operators, Expressions, Statements, Console I/O, Loops, Arrays, Methods
  • 2. Table of Contents 1. DataTypes 2. Operators 3. Expressions 4. Console I/O 5. Conditional Statements 6. Loops 7. Arrays 8. Methods 2
  • 4. IntegerTypes Integer types are: sbyte (-128 to 127): signed 8-bit byte (0 to 255): unsigned 8-bit short (-32,768 to 32,767): signed 16-bit ushort (0 to 65,535): unsigned 16-bit int (-2,147,483,648 to 2,147,483,647): signed 32-bit uint (0 to 4,294,967,295): unsigned 32-bit 4
  • 5. IntegerTypes (2) More integer types: long (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807): signed 64-bit ulong (0 to 18,446,744,073,709,551,615): unsigned 64-bit 5
  • 6. IntegerTypes – Example Measuring time Depending on the unit of measure we may use different data types: byte centuries = 20; // Usually a small number ushort years = 2000; uint days = 730480; ulong hours = 17531520; // May be a very big number Console.WriteLine("{0} centuries is {1} years, or {2} days, or {3} hours.", centuries, years, days, hours); 6
  • 7. Floating-Point Types Floating-point types are: float (±1.5 × 10−45 to ±3.4 × 1038): 32-bits, precision of 7 digits double (±5.0 × 10−324 to ±1.7 × 10308): 64-bits, precision of 15-16 digits The default value of floating-point types: Is 0.0F for the float type Is 0.0D for the double type 7
  • 8. Fixed-PointTypes There is a special fixed-point real number type: decimal (±1,0 × 10-28 to ±7,9 × 1028): 128-bits, precision of 28-29 digits Used for financial calculations with low loss of precision No round-off errors The default value of decimal type is: 0.0M (M is the suffix for decimal numbers) 8
  • 9. PI Precision – Example See below the difference in precision when using float and double: NOTE:The “f” suffix in the first statement! Real numbers are by default interpreted as double! One should explicitly convert them to float float floatPI = 3.141592653589793238f; double doublePI = 3.141592653589793238; Console.WriteLine("Float PI is: {0}", floatPI); Console.WriteLine("Double PI is: {0}", doublePI); 9
  • 10. Abnormalities in the Floating-Point Calculations Sometimes abnormalities can be observed when using floating-point numbers Comparing floating-point numbers can not be done directly with the == operator Example: float a = 1.0f; float b = 0.33f; float sum = 1.33f; bool equal = (a+b == sum); // False!!! Console.WriteLine("a+b={0} sum={1} equal={2}", a+b, sum, equal); 10
  • 11. The Boolean DataType The Boolean DataType: Is declared by the bool keyword Has two possible values: true and false Is useful in logical expressions The default value is false 11
  • 12. BooleanValues – Example Here we can see how boolean variables take values of true or false: int a = 1; int b = 2; bool greaterAB = (a > b); Console.WriteLine(greaterAB); // False bool equalA1 = (a == 1); Console.WriteLine(equalA1); // True 12
  • 13. The Character DataType The Character DataType: Represents symbolic information Is declared by the char keyword Gives each symbol a corresponding integer code Has a '0' default value Takes 16 bits of memory (from U+0000 to U+FFFF) 13
  • 14. Characters and Codes The example below shows that every symbol has an its unique code: char symbol = 'a'; Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol); symbol = 'b'; Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol); symbol = 'A'; Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol); 14
  • 15. The String DataType The String DataType: Represents a sequence of characters Is declared by the string keyword Has a default value null (no value) Strings are enclosed in quotes: Strings can be concatenated string s = "Microsoft .NET Framework"; 15
  • 16. Saying Hello – Example Concatenating the two names of a person to obtain his full name: NOTE: a space is missing between the two names!We have to add it manually string firstName = "Ivan"; string lastName = "Ivanov"; Console.WriteLine("Hello, {0}!", firstName); string fullName = firstName + " " + lastName; Console.WriteLine("Your full name is {0}.", fullName); 16
  • 17. The ObjectType The object type: Is declared by the object keyword Is the “parent” of all other types Can take any types of values according to the needs 17
  • 18. Using Objects Example of an object variable taking different types of data: object dataContainer = 5; Console.Write("The value of dataContainer is: "); Console.WriteLine(dataContainer); dataContainer = "Five"; Console.Write ("The value of dataContainer is: "); Console.WriteLine(dataContainer); 18
  • 20. DeclaringVariables When declaring a variable we: Specify its type Specify its name (called identifier) May give it an initial value The syntax is the following: Example: <data_type> <identifier> [= <initialization>]; int height = 200; 20
  • 21. Identifiers Identifiers may consist of: Letters (Unicode) Digits [0-9] Underscore "_" Identifiers Can begin only with a letter or an underscore Cannot be a C# keyword 21
  • 22. Identifiers (2) Identifiers Should have a descriptive name It is recommended to use only Latin letters Should be neither too long nor too short Note: In C# small letters are considered different than the capital letters (case sensitivity) 22
  • 23. Identifiers – Examples Examples of correct identifiers: Examples of incorrect identifiers: int new; // new is a keyword int 2Pac; // Cannot begin with a digit int New = 2; // Here N is capital int _2Pac; // This identifiers begins with _ string поздрав = "Hello"; // Unicode symbols used // The following is more appropriate: string greeting = "Hello"; int n = 100; // Undescriptive int numberOfClients = 100; // Descriptive // Overdescriptive identifier: int numberOfPrivateClientOfTheFirm = 100; 23
  • 25. Integer Literals Examples of integer literals The '0x' and '0X' prefixes mean a hexadecimal value, e.g. 0xA8F1 The 'u' and 'U' suffixes mean a ulong or uint type, e.g. 12345678U The 'l' and 'L' suffixes mean a long or ulong type, e.g. 9876543L 25
  • 26. Integer Literals – Example Note: the letter ‘l’ is easily confused with the digit ‘1’ so it’s better to use ‘L’!!! // The following variables are // initialized with the same value: int numberInHex = -0x10; int numberInDec = -16; // The following causes an error, because 234u is of type uint int unsignedInt = 234u; // The following causes an error, because 234L is of type long int longInt = 234L; 26
  • 27. Real Literals The real literals: Are used for values of type float and double May consist of digits, a sign and “.” May be in exponential formatting The “f” and “F” suffixes mean float The “d” and “D” suffixes mean double The default interpretation is double 27
  • 28. Real Literals – Example Example of incorrect float literal: A correct way to assign floating-point value (using also the exponential format): // The following causes an error // because 12.5 is double by default float realNumber = 12.5; // The following is the correct // way of assigning the value: float realNumber = 12.5f; // This is the same value in exponential format: realNumber = 1.25e+1f; 28
  • 29. Character Literals The character literals: Are used for values of the char type Consist of two single quotes surrounding the value: '<value>' The value may be: Symbol The code of the symbol Escaping sequence 29
  • 30. Escaping Sequences Escaping sequences are: Means of presenting a symbol that is usually interpreted otherwise (like ') Means of presenting system symbols (like the new line symbol) Common escaping sequences are:  ' for single quote  " for double quote  for backslash  n for new line 30
  • 31. Character Literals – Example Examples of different character literals: char symbol = 'a'; // An ordinary symbol symbol = 'u0061'; // Unicode symbol code in // a hexadecimal format symbol = '''; // Assigning the single quote symbol symbol = ''; // Assigning the backslash symbol symbol = "a"; // Incorrect: use single quotes 31
  • 32. String Literals String literals: Are used for values of the string type Consist of two double quotes surrounding the value: "<value>" May have a @ prefix which ignores the used escaping sequences The value is a sequence of character literals 32
  • 33. String Literals – Example Benefits of quoted strings (the @ prefix): In quoted strings " is used instead of ""! // Here is a string literal using escape sequences string quotation = ""Hello, Jude", he said."; string path = "C:WINNTDartsDarts.exe"; // Here is an example of the usage of @ quotation = @"""Hello, Jimmy!"", she answered."; path = @"C:WINNTDartsDarts.exe"; 33
  • 35. Categories of Operators in C# Category Operators Arithmetic + - * / % ++ -- Logical && || ^ ! Binary & | ^ ~ << >> Comparison == != < > <= >= Assignment = += -= *= /= %= &= |= ^= <<= >>= String concatenation + Type conversion is as typeof Other . [] () ?: new 35
  • 36. Operators Precedence Precedence Operators Highest ++ -- (postfix) new typeof ++ -- (prefix) + - (unary) ! ~ * / % + - << >> < > <= >= is as == != & Lower ^ 36
  • 37. Operators Precedence (2) Precedence Operators Higher | && || ?: Lowest = *= /= %= += -= <<= >>= &= ^= |= Parenthesis operator always has highest precedence Note: prefer using parentheses, even when it seems stupid to do so 37
  • 38. Arithmetic Operators Arithmetic operators +, -, * are the same as in math Division operator / if used on integers returns integer (without rounding) Remainder operator % returns the remainder from division of integers The special addition operator ++ increments a variable 38
  • 39. 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 39
  • 40. Logical Operators Logical operators take boolean operands and return boolean result Operator ! turns true to false and false to true Behavior of the operators &&, || and ^ (1 == true, 0 == false) : 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 40
  • 41. Logical Operators – Example Using the logical operators: 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 41
  • 42. 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) Behavior of the operators|, & and ^: 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 42
  • 43. Bitwise Operators (2) Bitwise operators are used on integer numbers (byte, sbyte, int, uint, long, ulong) Bitwise operators are applied bit by bit Examples: ushort a = 3; // 00000011 ushort b = 5; // 00000101 Console.WriteLine( a | b); // 00000111 Console.WriteLine( a & b); // 00000001 Console.WriteLine( a ^ b); // 00000110 Console.WriteLine(~a & b); // 00000100 Console.WriteLine( a<<1 ); // 00000110 Console.WriteLine( a>>1 ); // 00000001 43
  • 44. 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 == b); // False Console.WriteLine(a == a); // True Console.WriteLine(a != ++b); // False 44
  • 45. 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 Console.WriteLine(x += 3); // 10 Console.WriteLine(x /= 2); // 5 45
  • 46. Other Operators String concatenation operator + is used to concatenate strings If the second operand is not a string, it is converted to string automatically string first = "First"; string second = "Second"; Console.WriteLine(first + second); // FirstSecond string output = "The number is : "; int number = 5; Console.WriteLine(output + number); // The number is : 5 46
  • 47. Other Operators (2) 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 47
  • 48. Other Operators (3) Conditional operator ?: has the form (if b is true then the result is x else the result is 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 b ? x : y 48
  • 49. Other Operators – Example Using some other operators: 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 49
  • 50. Type Conversions Example of implicit and explicit conversions: Note: explicit conversion may be used even if not required by the compiler float heightInMeters = 1.74f; // Explicit conversion double maxHeight = heightInMeters; // Implicit double minHeight = (double) heightInMeters; // Explicit float actualHeight = (float) maxHeight; // Explicit float maxHeightFloat = maxHeight; // Compilation error! 50
  • 52. Expressions Expressions are sequences of operators, literals and variables that are evaluated to some value Examples: int r = (150-20) / 2 + 5; // Expression for calculation of circle area double surface = Math.PI * r * r; // Expression for calculation of circle perimeter double perimeter = 2 * Math.PI * r; 52
  • 53. Using to the Console Printing / Reading Strings and Numbers
  • 54. The Console Class Provides methods for input and output Input  Read(…) – reads a single character  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 54
  • 55. Console.Write(…) Printing more than one variable using a formatting string int a = 15; ... Console.Write(a); // 15 Printing an integer variable 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 55
  • 56. Console.WriteLine(…) Printing more than one variable using a formatting string string str = "Hello C#!"; ... Console.WriteLine(str); Printing a string variable string name = "Marry"; int year = 1987; ... Console.Write("{0} was born in {1}.", name, year); // Marry was born in 1987. Next printing will start from the next line 56
  • 57. Printing to the Console – Example static void Main() { string name = "Peter"; int age = 18; string town = "Sofia"; Console.Write("{0} is {1} years old from {2}.", name, age, town); // Result: Peter is 18 years old from Sofia. Console.Write("This is on the same line!"); Console.WriteLine("Next sentence will be" + " on a new line."); Console.WriteLine("Bye, bye, {0} from {1}.", name, town); } 57
  • 58. Reading from the Console 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() 58
  • 59. 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); 59
  • 60. Reading NumeralTypes Numeral types can not be read directly from the console To read a numeral type do 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); 60
  • 61. Reading NumeralTypes (2) Another way to parse string to numeral type is to use int.TryParse(…) method Sets default value for the type if the parse fails Returns bool  True if the parse is successfull  False if it fails int a; string line = Console.ReadLine(); int.TryParse(line, out a); The result from the parse will be assigned to the variable parseResult 61
  • 62. Converting Strings to Numbers Numeral types have a method Parse(…) for extracting the numeral value from a string  int.Parse(string) – string  int  long.Parse(string) – string  long  float.Parse(string) – string  float  Causes FormatException in case of error 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 62
  • 64. 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; } 64
  • 65. 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); } 65
  • 66. 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 (expression) { statement1; } else { statement2; } 66
  • 67. 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."); } 67
  • 68. 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; 68
  • 69. 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."); } } 69
  • 70. 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; } 70
  • 72. HowTo Use While Loop? The simplest and most frequently used loop The repeat condition Returns a boolean result of true or false Also called loop condition while (condition) { statements; } 72
  • 73. While Loop – Example int counter = 0; while (counter < 10) { Console.WriteLine("Number : {0}", counter); counter++; } 73
  • 74. Using Do-While Loop Another loop structure is: The block of statements is repeated While the boolean loop condition holds The loop is executed at least once do { statements; } while (condition); 74
  • 75. Factorial – 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); } 75
  • 76. For Loops The typical for loop syntax is: Consists of Initialization statement Boolean test expression Update statement Loop body block for (initialization; test; update) { statements; } 76
  • 77. N^M – Example Calculating n to power m (denoted as n^m): static void Main() { int n = int.Parse(Console.ReadLine()); int m = int.Parse(Console.ReadLine()); decimal result = 1; for (int i=0; i<m; i++) { result *= n; } Console.WriteLine("n^m = " + result); } 77
  • 78. For-Each Loops The typical foreach loop syntax is: 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 foreach (Type element in collection) { statements; } 78
  • 79. 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 79
  • 80. 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; } … } 80
  • 81. Nested Loops – Examples Print all combinations fromTOTO 6/49 static void Main() { int i1, i2, i3, i4, i5, i6; for (i1 = 1; i1 <= 44; i1++) for (i2 = i1 + 1; i2 <= 45; i2++) for (i3 = i2 + 1; i3 <= 46; i3++) for (i4 = i3 + 1; i4 <= 47; i4++) for (i5 = i4 + 1; i5 <= 48; i5++) for (i6 = i5 + 1; i6 <= 49; i6++) Console.WriteLine("{0} {1} {2} {3} {4} {5}", i1, i2, i3, i4, i5, i6); } Warning: execution of this code could take too long time. 81
  • 83. What are Arrays? 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) 0 1 2 3 4Array of 5 elements Element index Element of an array … … … … … 83
  • 84. Declaring Arrays Declaration defines the type of the elements Square brackets [] mean "array" Examples: Declaring array of integers: Declaring array of strings: int[] myIntArray; string[] myStringArray; 84
  • 85. Creating Arrays Use the operator new Specify array length Example creating (allocating) array of 5 integers: myIntArray = new int[5]; myIntArray managed heap (dynamic memory) 0 1 2 3 4 … … … … … 85
  • 86. Creating and Initializing Arrays Creating and initializing can be done together: The new operator is not required when using curly brackets initialization myIntArray = {1, 2, 3, 4, 5}; myIntArray managed heap (dynamic memory) 0 1 2 3 4 … … … … … 86
  • 87. 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" }; 87
  • 88. How to Access Array Element? 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 88
  • 89. Reversing an Array – Example Reversing the contents of an array int[] array = new int[] {1, 2, 3, 4, 5}; // Get array size int length = array.Length; // Declare and create the reversed array int[] reversed = new int[length]; // Initialize the reversed array for (int index = 0; index < length; index++) { reversed[length-index-1] = array[index]; } 89
  • 90. Processing Arrays: foreach How foreach loop works? type – the type of the element value – local name of variable array – processing array Used when no indexing is needed All elements are accessed one by one Elements can not be modified (read only) foreach (type value in array) 90
  • 91. Processing Arrays Using foreach – Example Print all elements of a string[] array: string[] capitals = { "Sofia", "Washington", "London", "Paris" }; foreach (string capital in capitals) { Console.WriteLine(capital); } 91
  • 92. Multidimensional Arrays Multidimensional arrays have more than one dimension (2, 3, …) The most important multidimensional arrays are the 2- dimensional  Known as matrices or tables Example of matrix of integers with 2 rows and 4 columns: 5 0 -2 4 5 6 7 8 0 1 2 3 0 1 92
  • 93. Declaring and Creating Multidimensional Arrays Declaring multidimensional arrays: Creating a multidimensional array Use new keyword Must specify the size of each dimension int[,] intMatrix; float[,] floatMatrix; string[,,] strCube; int[,] intMatrix = new int[3, 4]; float[,] floatMatrix = new float[8, 2]; string[,,] stringCube = new string[5, 5, 5]; 93
  • 94. Creating and Initializing Multidimensional Arrays Creating and initializing with values multidimensional array: Matrices are represented by a list of rows  Rows consist of list of values The first dimension comes first, the second comes next (inside the first) 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) 94
  • 95. Reading Matrix – 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]; for (int row=0; row<rows; row++) { for (int col=0; col<cols; col++) { Console.Write("matrix[{0},{1}] = ", row, col); matrix[row, col] = int.Parse(Console.ReadLine()); } } 95
  • 96. Printing Matrix – 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(); } 96
  • 98. What Is String? Strings are sequences of characters Each character is a Unicode symbol Represented by the string data type in C# (System.String) Example: string s = "Hello, C#"; H e l l o , C #s 98
  • 99. The System.String Class Strings are represented by System.String objects in .NET Framework String objects contain an immutable (read-only) sequence of characters Strings use Unicode in to support multiple languages and alphabets Strings are stored in the dynamic memory (managed heap) System.String is reference type 99
  • 100. The System.String Class (2) String objects are like arrays of characters (char[]) Have fixed length (String.Length) Elements can be accessed directly by index  The index is in the range [0...Length-1] string s = "Hello!"; int len = s.Length; // len = 6 char ch = s[1]; // ch = 'e' 0 1 2 3 4 5 H e l l o ! index = s[index] = 100
  • 101. Strings – Example static void Main() { string s = "Stand up, stand up, Balkan Superman."; Console.WriteLine("s = "{0}"", s); Console.WriteLine("s.Length = {0}", s.Length); for (int i = 0; i < s.Length; i++) { Console.WriteLine("s[{0}] = {1}", i, s[i]); } } 101
  • 102. Declaring Strings There are two ways of declaring string variables: Using the C# keyword string Using the .NET's fully qualified class name System.String The above three declarations are equivalent string str1; System.String str2; String str3; 102
  • 103. Creating Strings Before initializing a string variable has null value Strings can be initialized by: Assigning a string literal to the string variable Assigning the value of another string variable Assigning the result of operation of type string 103
  • 104. Creating Strings (2) Not initialized variables has value of null Assigning a string literal Assigning from another string variable Assigning from the result of string operation string s; // s is equal to null string s = "I am a string literal!"; string s2 = s; string s = 42.ToString(); 104
  • 105. Reading and Printing Strings Reading strings from the console Use the method Console.ReadLine() string s = Console.ReadLine(); Console.Write("Please enter your name: "); string name = Console.ReadLine(); Console.Write("Hello, {0}! ", name); Console.WriteLine("Welcome to our party!"); Printing strings to the console Use the methods Write() and WriteLine() 105
  • 106. A number of ways exist to compare two strings: Dictionary-based string comparison  Case-insensitive  Case-sensitive Comparing Strings int result = string.Compare(str1, str2, true); // result == 0 if str1 equals str2 // result < 0 if str1 if before str2 // result > 0 if str1 if after str2 string.Compare(str1, str2, false); 106
  • 107. Comparing Strings – Example Finding the first string in a lexicographical order from a given list of strings: string[] towns = {"Sofia", "Varna", "Plovdiv", "Pleven", "Bourgas", "Rousse", "Yambol"}; 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); 107
  • 108. Concatenating Strings There are two ways to combine strings:  Using the Concat() method  Using the + or the += operators Any object can be appended to string string str = String.Concat(str1, str2); string str = str1 + str2 + str3; string str += str1; string name = "Peter"; int age = 22; string s = name + " " + age; //  "Peter 22" 108
  • 109. Searching in Strings Finding a character or substring within given string  First occurrence  First occurrence starting at given position  Last occurrence IndexOf(string str) IndexOf(string str, int startIndex) LastIndexOf(string) 109
  • 110. Searching in Strings – Example string str = "C# Programming Course"; int index = str.IndexOf("C#"); // index = 0 index = str.IndexOf("Course"); // index = 15 index = str.IndexOf("COURSE"); // index = -1 // IndexOf is case-sensetive. -1 means not found index = str.IndexOf("ram"); // index = 7 index = str.IndexOf("r"); // index = 4 index = str.IndexOf("r", 5); // index = 7 index = str.IndexOf("r", 8); // index = 18 0 1 2 3 4 5 6 7 8 9 10 11 12 13 … C # P r o g r a m m i n g … index = s[index] = 110
  • 111. Extracting Substrings Extracting substrings  str.Substring(int startIndex, int length)  str.Substring(int startIndex) string filename = @"C:PicsRila2009.jpg"; string name = filename.Substring(8, 8); // name is Rila2009 string filename = @"C:PicsSummer2009.jpg"; string nameAndExtension = filename.Substring(8); // nameAndExtension is Summer2009.jpg 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 C : P i c s R i l a 2 0 0 5 . j p g 111
  • 112. Splitting Strings To split a string by given separator(s) use the following method: Example: string[] Split(params char[]) string listOfBeers = "Amstel, Zagorka, Tuborg, Becks."; string[] beers = listOfBeers.Split(' ', ',', '.'); Console.WriteLine("Available beers are:"); foreach (string beer in beers) { Console.WriteLine(beer); } 112
  • 113. Replacing and Deleting Substrings Replace(string, string) – replaces all occurrences of given string with another  The result is new string (strings are immutable) Remove(index, length) – deletes part of a string and produces new string as result string cocktail = "Vodka + Martini + Cherry"; string replaced = cocktail.Replace("+", "and"); // Vodka and Martini and Cherry string price = "$ 1234567"; string lowPrice = price.Remove(2, 3); // $ 4567 113
  • 114. Changing Character Casing Using method ToLower() Using method ToUpper() string alpha = "aBcDeFg"; string lowerAlpha = alpha.ToLower(); // abcdefg Console.WriteLine(lowerAlpha); string alpha = "aBcDeFg"; string upperAlpha = alpha.ToUpper(); // ABCDEFG Console.WriteLine(upperAlpha); 114
  • 115. Trimming White Space Using method Trim() Using method Trim(chars) Using TrimStart() and TrimEnd() string s = " example of white space "; string clean = s.Trim(); Console.WriteLine(clean); string s = " tnHello!!! n"; string clean = s.Trim(' ', ',' ,'!', 'n','t'); Console.WriteLine(clean); // Hello string s = " C# "; string clean = s.TrimStart(); // clean = "C# " 115
  • 116. Constructing Strings Strings are immutable Concat(), Replace(), Trim(), ... return new string, do not modify the old one Do not use "+" for strings in a loop! It runs very, very inefficiently! public static string DupChar(char ch, int count) { string result = ""; for (int i=0; i<count; i++) result += ch; return result; } Very bad practice. Avoid this! 116
  • 117. Changing the Contents of a String – StringBuilder Use the System.Text.StringBuilder class for modifiable strings of characters: Use StringBuilder if you need to keep adding characters to a string public static string ReverseString(string s) { StringBuilder sb = new StringBuilder(); for (int i = s.Length-1; i >= 0; i--) sb.Append(s[i]); return sb.ToString(); } 117
  • 118. StringBuilder keeps a buffer memory, allocated in advance Most operations use the buffer memory and do not allocate new objects The StringBuilder Class H e l l o , C # !StringBuilder: Length=9 Capacity=15 Capacity used buffer (Length) unused buffer 118
  • 119. StringBuilder – Example Extracting all capital letters from a string public static string ExtractCapitals(string s) { StringBuilder result = new StringBuilder(); for (int i = 0; i<s.Length; i++) { if (Char.IsUpper(s[i])) { result.Append(s[i]); } } return result.ToString(); } 119
  • 120. Method ToString() All classes have public virtual method ToString() Returns a human-readable, culture-sensitive string representing the object Most .NET Framework types have own implementation of ToString()  int, float, bool, DateTime int number = 5; string s = "The number is " + number.ToString(); Console.WriteLine(s); // The number is 5 120
  • 121. Method ToString(format) We can apply specific formatting when converting objects to string  ToString(formatString) method int number = 42; string s = number.ToString("D5"); // 00042 s = number.ToString("X"); // 2A // Consider the default culture is Bulgarian s = number.ToString("C"); // 42,00 лв double d = 0.375; s = d.ToString("P2"); // 37,50 % 121
  • 122. Formatting Strings The formatting strings are different for the different types Some formatting strings for numbers:  D – number (for integer types)  C – currency (according to current culture)  E – number in exponential notation  P – percentage  X – hexadecimal number  F – fixed point (for real numbers) 122
  • 123. Method String.Format() Applies templates for formatting strings Placeholders are used for dynamic text Like Console.WriteLine(…) string template = "If I were {0}, I would {1}."; string sentence1 = String.Format( template, "developer", "know C#"); Console.WriteLine(sentence1); // If I were developer, I would know C#. string sentence2 = String.Format( template, "elephant", "weigh 4500 kg"); Console.WriteLine(sentence2); // If I were elephant, I would weigh 4500 kg. 123
  • 124. Composite Formatting The placeholders in the composite formatting strings are specified as follows: Examples: {index[,alignment][:formatString]} double d = 0.375; s = String.Format("{0,10:F5}", d); // s = " 0,37500" int number = 42; Console.WriteLine("Dec {0:D} = Hex {1:X}", number, number); // Dec 42 = Hex 2A 124
  • 125. Formatting Dates Dates have their own formatting strings d, dd – day (with/without leading zero) M, MM – month yy, yyyy – year (2 or 4 digits) h, HH, m, mm, s, ss – hour, minute, second DateTime now = DateTime.Now; Console.WriteLine( "Now is {0:d.MM.yyyy HH:mm:ss}", now); // Now is 31.11.2009 11:30:32 125
  • 126. форум програмиране,форум уеб дизайн курсове и уроци по програмиране,уеб дизайн – безплатно програмиранеза деца – безплатни курсове и уроци безплатен SEO курс -оптимизация за търсачки уроци по уеб дизайн, HTML,CSS, JavaScript,Photoshop уроци по програмиранеи уеб дизайн за ученици ASP.NET MVCкурс – HTML,SQL,C#,.NET,ASP.NETMVC безплатен курс"Разработка на софтуер в cloud среда" BG Coder -онлайн състезателна система -online judge курсове и уроци по програмиране,книги – безплатно отНаков безплатен курс"Качествен програменкод" алго академия – състезателно програмиране,състезания ASP.NET курс -уеб програмиране,бази данни, C#,.NET,ASP.NET курсове и уроци по програмиране– Телерик академия курсмобилни приложения сiPhone, Android,WP7,PhoneGap freeC#book, безплатна книга C#,книга Java,книга C# Дончо Минков -сайт за програмиране Николай Костов -блог за програмиране C#курс,програмиране,безплатно C# Language Overview (Part I)

Notas del editor

  1. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  2. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  3. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  4. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  5. 07/16/96
  6. 07/16/96
  7. 07/16/96
  8. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  9. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  10. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  11. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*