Chapter 2 materials
Chapter 2 materials
2
Example
3
Syntax
4
Identifiers and Keywords
● Identifiers are names that programmers choose for their classes, methods, variables, and so on.
● An identifier must be a whole word, essentially made up of Unicode characters starting
with a letter or underscore.
● C# identifiers are case sensitive.
● By convention, parameters, local variables, and private fields should be in camel case (e.g.,
myVariable ), and all other identifiers should be in Pascal case (e.g., MyMethod ).
5
Identifiers and Keywords
6
Identifiers and Keywords
● If we want to use an identifier that clashes with a reserved keyword, we can do so by qualifying
it with the @ prefix;
● Example: int using = 234; // Illegal
int @using = 234; //Legal
● Contextual keywords: Some keywords are contextual, meaning that we can use them as
identifiers without an @ symbol:
7
Literals, Punctuators, and Operators
● Literals are primitive pieces of data lexically embedded into the program. The literals we
used in our example program are 12 and 30 .
● Punctuators help demarcate the structure of the program. An example is the semi‐colon, which
terminates a statement. Statements can wrap multiple lines:
Console.WriteLine
(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10);
● An operator transforms and combines expressions. Most operators in C# are denoted with a
symbol, such as the multiplication operator, * . These are the operators we used in our example
program: = * . ()
8
Comment
● C# offers two different styles of source-code documentation: single-line comments and multiline
comments.
● A single-line comment begins with a double forward slash and continues until the end of the line;
for example: int x = 3; // Comment about assigning 3 to x
● A multiline comment begins with /* and ends with */ ; for example:
int x = 3; /* This is a comment that
spans two lines */
9
Data Type
● C# is a strongly-typed language.
● It means we must declare the type of a variable that indicates the kind of values it is going to
store, such as integer, float, decimal, text, etc.
● Example:
string stringVar = "Hello World!!";
int intVar = 100;
float floatVar = 10.2f;
char charVar = 'A';
bool boolVar = true;
10
Data Type
● C# mainly categorized data types in two types: Value types and Reference types.
● Value types include simple types (such as int, float, bool, and char), enum types, struct types, and
Nullable value types.
● Reference types include class types, interface types, delegate types, and array types.
11
Predefined Data Types
12
Predefined Data Types
13
Default Values
// C# 7.1 onwards
int i = default; // 0
float f = default;// 0
decimal d = default;// 0
bool b = default;// false
char c = default;// '\0'
14
Conversions
● The values of certain data types are automatically converted to different data types in C#. This is
called an implicit conversion.
● Example:
int i = 345;
float f = i;
Console.WriteLine(f); //output: 345
15
Conversions
● Conversions from int, uint, long, or ulong to float and from long or ulong to double may cause a loss of
precision. No data type implicitly converted to the char type.
● However, not all data types are implicitly converted to other data types. For example, int type cannot be
converted to uint implicitly. It must be specified explicitly.
● Example:
public static void Main()
{
int i = 100;
uint u = (uint) i;
Console.Write(i);
}
16
Value Type
● A data type is a value type if it holds a data value within its own memory space.
● It means the variables of these data types directly contain values.
● For example, consider integer variable int i = 100;
● The system stores 100 in the memory space allocated for the variable i.
17
Value Type
18
class A{
static void ChangeValue(int x)
{
x = 200;
Console.WriteLine(x);
}
Console.WriteLine(i);
ChangeValue(i);
Console.WriteLine(i);
}
}
19
Reference Type
● Unlike value types, a reference type doesn't store its value directly.
● Instead, it stores the address where the value is being stored.
● In other words, a reference type contains a pointer to another memory location that holds the
data.
● For example, consider the following string variable:
string s = "Hello World!!";
20
Reference Type
● As you can see in the above image, the system selects a random location in memory (0x803200)
for the variable s. The value of a variable s is 0x600000, which is the memory address of the
actual data value. Thus, reference type stores the address of the location where the actual value
is stored instead of the value itself.
● The followings are reference type data types:
○ String
○ Arrays (even if their elements are value types)
○ Class
○ Delegate
21
Reference Type
class B{
static void ChangeReferenceType(Student std2)
{
std2.StudentName = "Ram";
}
ChangeReferenceType(std1);
Console.WriteLine(std1.StudentName);
}
}
22
Operators
● Operators in C# are some special symbols that perform some action on operands.
● In mathematics, the plus symbol (+) do the sum of the left and right numbers. In the same way,
C# includes various operators for different types of operations.
● Example: + Operator
int x = 5 + 5;
int y = 10 + x;
int z = x + y;
string greet = “Hello “+ “World!”;
string greet1 = greet + name;
23
Operators
24
Arithmetic Operator
● The arithmetic operators perform arithmetic operations on all the numeric type operands such as
sbyte, byte, short, ushort, int, uint, long, ulong, float, double, and decimal.
25
Assignment Operators
● The assignment operator = assigns its right had value to its left-hand variable, property, or
indexer. It can also be used with other arithmetic, Boolean logical, and bitwise operators.
26
Comparison Operators
● Comparison operators compare two numeric operands and returns true or false.
27
Equality Operators
● The equality operator checks whether the two operands are equal or not.
28
Boolean Logical Operators
29
Bitwise and Bit Shift Operators
● The bitwise and shift operators include unary bitwise complement, binary left and right shift,
unsigned right shift, and the binary logical AND, OR, and exclusive OR operators.
30
Bitwise OR
31
using System;
namespace Operator
{
class BitWiseOR
{
public static void Main(string[] args)
{
int firstNumber = 14, secondNumber = 11, result;
result = firstNumber | secondNumber;
Console.WriteLine("{0} | {1} = {2}", firstNumber, secondNumber, result);
}
}
}
32
Exercise
33
Member access operators
34
Exercise
35
Type-cast operators
36
is operator
● The is operator checks if the run-time type of an expression result is compatible with a given type.
● The is operator also tests an expression result against a pattern.
● Example: E is T
class C{
static void Main(string[] args){
int i = 23;
object iBoxed = i;
int? jNullable = 7;
if (iBoxed is int a && jNullable is int b)
{
Console.WriteLine(a + b); // output 30
}
}
}
37
Exercise
38
Operator Evaluation & Precedence
● Evaluation of the operands in an expression starts from left to right. If multiple operators are
used in an expression, then the operators with higher priority are evaluated before the operators
with lower priority.
39
40
Statements
● C# provides many decision-making statements that help the flow of the C# program based on
certain logical conditions.
● C# includes the following flavors of if statements:
○ if statement
○ else-if statement
○ else statement
41
if Statement
● The if statement contains a boolean condition followed by a single or multi-line code block to be
executed.
● At runtime, if a boolean condition evaluates to true, then the code block will be executed,
otherwise not.
● Syntax:
if(condition)
{
// code block to be executed when if condition evaluates to true
}
42
if Statement : Example
if (i < j)
{
Console.WriteLine("i is less than j");
}
if (i > j)
{
Console.WriteLine("i is greater than j");
}
43
else if Statement
44
else if Statement : Example
if (i == j)
{
Console.WriteLine("i is equal to j");
}
else if (i > j)
{
Console.WriteLine("i is greater than j");
}
else if (i < j)
{
Console.WriteLine("i is less than j");
}
45
Exercise : else, nested if etc
46
Ternary Operator ?:
var result = x > y ? "x is greater than y" : "x is less than y";
Console.WriteLine(result);
47
Switch Statement
● The switch statement can be used instead of if else statement when you want to test a variable against
three or more conditions.
● Syntax:
switch(match expression/variable)
{
case constant-value:
statement(s) to be executed;
break;
default:
statement(s) to be executed;
break;
}
48
for Loop
49
for Loop : Example
Note: Practice with nested for loop, reverse for loop etc
50
while Loop
● C# provides the while loop to repeatedly execute a block of code as long as the specified
condition returns true.
● Syntax:
While(condition)
{
//code block
}
51
while Loop : Example
int i = 0; // initialization
i++; // increment
}
52
Do while Loop
● The do while loop is the same as while loop except that it executes the code block at least once.
● Syntax:
do
{
//code block
} while(condition);
● Example:
int i = 0;
do
{
Console.WriteLine("i = {0}", i);
i++;
} while (i < 5);
53
Array
● A variable is used to store a literal value, whereas an array is used to store multiple literal values.
● An array is the data structure that stores a fixed number of literal values (elements) of the same
data type. Array elements are stored contiguously in the memory.
● In C#, an array can be of three types: single-dimensional, multidimensional, and jagged array.
● Syntax:
int[] evenNums; // integer array
string[] cities; // string array
54
Array : Example
Console.WriteLine(evenNums[0]); //prints 2
Console.WriteLine(evenNums[1]); //prints 4
55
Array : Example
int[] evenNums = { 2, 4, 6, 8, 10 };
56
Array : Example
57
Multidimensional Arrays
58
Multidimensional Arrays : Example
// or
int[,] arr2d = {
{1, 2},
{3, 4},
{5, 6}
};
59
Multidimensional Arrays : Example
60
Multidimensional Arrays : Example
62
Jagged Arrays : Example
63
Namespace
64
Namespace : Example
namespace College
{
class Student
{
class Course
{
}
}
65
Happy Coding !!!
66