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

Chapter 2 materials

Uploaded by

my689013
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Chapter 2 materials

Uploaded by

my689013
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

The C# Language Basics

Er. Riddhi K. Shrestha


A First C# Program

2
Example

3
Syntax

● C# syntax is inspired by C and C++ 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

● Keywords are names that mean something special to the compiler.


● Most keywords are reserved, which means that you can’t use them as identifiers.
● C# reserved 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

● Every data type has a default value.


● Numeric type is 0, boolean has false, and char has '\0' as default value.
● Use the default(typename) to assign a default value of the data type or C# 7.1 onward, use default literal
int i = default(int); // 0
float f = default(float);// 0
decimal d = default(decimal);// 0
bool b = default(bool);// false
char c = default(char);// '\0'

// 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

● The following data types are all of value type:


○ bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort
● Passing Value Type Variables:
● When you pass a value-type variable from one method to another, the system creates a separate
copy of a variable in another method. If value got changed in the one method, it wouldn't affect
the variable in another method.

18
class A{
static void ChangeValue(int x)
{
x = 200;

Console.WriteLine(x);
}

static void Main(string[] args)


{
int i = 100;

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";
}

static void Main(string[] args)


{
Student std1 = new Student();
std1.StudentName = "Hari";

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

● C# includes the following categories of operators:


○ Arithmetic operators
○ Assignment operators
○ Comparison operators
○ Equality operators
○ Boolean logical operators
○ Bitwise and shift operators
○ Member access operators
○ Type-cast 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

● The Boolean logical operators perform a logical operation on bool operands.

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

● Bitwise OR operator is represented by |.


● It performs bitwise OR operation on the corresponding bits of two operands.
● If either of the bits is 1, the result is 1. Otherwise the result is 0.
● If the operands are of type bool, the bitwise OR operation is equivalent to logical OR operation
between them.

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

● Several operators and expressions to access a type member.


● These operators include member access (.), array element or indexer access ([]), index-from-end
(^), range (..), null-conditional operators (?. and ?[]), and method invocation (()). These include the
null-conditional member access (?.), and indexer access (?[]) operators.
● Member access expression .
○ to access a member of a namespace or a type
○ Example: using System.Collections.Generic;

34
Exercise

35
Type-cast operators

● These operators and expressions perform type checking or type conversion.


● Following are the type-cast operators:
○ is
○ as
○ cast
○ typeof
● The is operator checks if the run-time type of an expression is compatible with a given type.
● The as operator explicitly converts an expression to a given type if its run-time type is compatible with
that type.
● Cast expressions perform an explicit conversion to a target type.
● The typeof operator obtains the System.Type instance for a type.

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

int i = 10, j = 20;

if (i < j)
{
Console.WriteLine("i is less than j");
}

if (i > j)
{
Console.WriteLine("i is greater than j");
}

43
else if Statement

● Multiple else if statements can be used after an if statement.


● It will only be executed when the if condition evaluates to false.
● So, either if or one of the else if statements can be executed, but not both.
● Syntax:
if(condition1)
{
// code block to be executed when if condition1 evaluates to true
}
else if(condition2)
{
// code block to be executed when
// condition1 evaluates to flase
// condition2 evaluates to true
}
...

44
else if Statement : Example

int i = 10, j = 20;

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 ?:

● C# includes a decision-making operator ?: which is called the conditional operator or ternary


operator.
● It is the short form of the if else conditions.
● Syntax: condition ? statement 1 : statement 2
● Example:
int x = 20, y = 10;

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

● The for keyword indicates a loop in C#.


● The for loop executes a block of statements repeatedly until the specified condition returns false.
● Syntax:
for (initializer; condition; iterator)
{
//code block
}

49
for Loop : Example

for(int i = 0; i < 10; i++)


{
Console.WriteLine("Value of i: {0}", i);
}

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

while (i < 10) // condition


{
Console.WriteLine("i = {0}", i);

i++; // increment
}

Note: Practice with nested while loop

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

int[] evenNums = new int[5]{ 2, 4, 6, 8, 10 };


string[] cities = new string[3]{ “Pokhara", "London", “SNew York" };

54
Array : Example

int[] evenNums = new int[5];


evenNums[0] = 2;
evenNums[1] = 4;
//evenNums[6] = 12; //Throws run-time exception IndexOutOfRange

Console.WriteLine(evenNums[0]); //prints 2
Console.WriteLine(evenNums[1]); //prints 4

55
Array : Example

int[] evenNums = { 2, 4, 6, 8, 10 };

for(int i = 0; i < evenNums.Length; i++)


Console.WriteLine(evenNums[i]);

for(int i = 0; i < evenNums.Length; i++)


evenNums[i] = evenNums[i] + 10; // update the value of each element by 10

56
Array : Example

int[] evenNums = { 2, 4, 6, 8, 10};


string[] cities = { “Pokhara", "London", "New York" };

foreach(var item in evenNums)


Console.WriteLine(item);

foreach(var city in cities)


Console.WriteLine(city);

57
Multidimensional Arrays

● C# supports multidimensional arrays.


● The multidimensional array can be declared by adding commas in the square brackets. For
example, [,] declares two-dimensional array, [, ,] declares three-dimensional array, [, , ,] declares
four-dimensional array, and so on.
● So, in a multidimensional array, no of commas = No of Dimensions - 1.
● Syntax:
int[,] arr2d; // two-dimensional array
int[, ,] arr3d; // three-dimensional array
int[, , ,] arr4d ; // four-dimensional array
int[, , , ,] arr5d; // five-dimensional array

58
Multidimensional Arrays : Example

int[,] arr2d = new int[3,2]{


{1, 2},
{3, 4},
{5, 6}
};

// or
int[,] arr2d = {
{1, 2},
{3, 4},
{5, 6}
};

59
Multidimensional Arrays : Example

int[,] arr2d = new int[3,2]{


{1, 2},
{3, 4},
{5, 6}
};

arr2d[0, 0]; //returns 1


arr2d[0, 1]; //returns 2
arr2d[1, 0]; //returns 3
arr2d[1, 1]; //returns 4
arr2d[2, 0]; //returns 5
arr2d[2, 1]; //returns 6
//arr2d[3, 0]; //throws run-time error as there is no 4th row

60
Multidimensional Arrays : Example

int[, ,] arr3d1 = new int[1, 2, 2]{


{ { 1, 2}, { 3, 4} }
};

int[, ,] arr3d2 = new int[2, 2, 2]{


{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} }
};

int[, ,] arr3d3 = new int[2, 2, 3]{


{ { 1, 2, 3}, {4, 5, 6} },
{ { 7, 8, 9}, {10, 11, 12} }
};

arr3d2[0, 0, 0]; // returns 1


arr3d2[0, 0, 1]; // returns 2
arr3d2[0, 1, 0]; // returns 3
arr3d2[0, 1, 1]; // returns 4 61
Jagged Arrays

● A jagged array is an array of array.


● Jagged arrays store arrays instead of literal values.
● A jagged array is initialized with two square brackets [][].
● The first bracket specifies the size of an array, and the second bracket specifies the dimensions
of the array which is going to be stored.
● Syntax:
int[][] jArray1 = new int[2][]; // can include two single-dimensional arrays
int[][,] jArray2 = new int[3][,]; // can include three two-dimensional arrays

62
Jagged Arrays : Example

int[][,] jArray = new int[2][,];

jArray[0] = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };


jArray[1] = new int[2, 2] { { 7, 8 }, { 9, 10 } };

jArray[0][1, 1]; //returns 4

jArray[1][1, 0]; //returns 9

jArray[1][1, 1]; //returns 10

63
Namespace

● Namespaces play an important role in managing related classes in C#.


● The .NET Framework uses namespaces to organize its built-in classes.
● For example, there are some built-in namespaces in .NET such as System, System.Linq,
System.Web, etc. Each namespace contains related classes.
● A namespace is a container for classes and namespaces.
● The namespace also gives unique names to its classes thereby you can have the same class name
in different namespaces.

64
Namespace : Example

namespace College
{
class Student
{

class Course
{

}
}

65
Happy Coding !!!

66

You might also like