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

CSharpAlltopics

The document provides an introduction to C# programming, focusing on the 'Hello World!' program as a foundational exercise. It covers key concepts such as keywords, identifiers, variable declaration, primitive data types, and basic operators in C#. Additionally, it highlights best practices for naming variables and includes examples for better understanding.

Uploaded by

Saurabh Singh
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)
5 views

CSharpAlltopics

The document provides an introduction to C# programming, focusing on the 'Hello World!' program as a foundational exercise. It covers key concepts such as keywords, identifiers, variable declaration, primitive data types, and basic operators in C#. Additionally, it highlights best practices for naming variables and includes examples for better understanding.

Uploaded by

Saurabh Singh
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/ 155

Complete Note Of Csharp(C#):

Introduction
The "Hello World!" program is a foundational component when acquainting oneself with a new
programming language. Its primary function is to display the text "Hello World!" on the output screen,
serving as an introductory exercise to grasp essential syntax and language requirements.

"Hello World!" in C#

Code

// Hello World! program


namespace HelloWorld
{
class Hello {
static void Main(string[] args)
{
System.Console.WriteLine("Hello World!");
}
}
}

Output
When executed, the program outputs:

Hello World!

Program Breakdown
1. Comments:

// Hello World! Program : Marks the beginning of a comment in C#. Comments are for developer

understanding and are not executed by the compiler.

2. Namespace:

: Defines a namespace called HelloWorld . Namespaces act as


namespace HelloWorld {...}

containers for classes, methods, and other namespaces.

3. Class Definition:

class Hello {...} : Creates a class named Hello . In C#, class creation is mandatory as it is an
object-oriented programming language.

4. Main Method:

static void Main(string[] args) {...} : The Main() method is the starting point of execution for

every C# program. It must be inside a class and follows a specific signature.

5. Print "Hello World!":

Complete Note Of Csharp(C#): 1


System.Console.WriteLine("Hello World!"); : This line of code prints "Hello World!" to the output
screen. Further details on its functionality will be covered in subsequent chapters.

Alternative Implementation

Code

// Hello World! program


using System;

namespace HelloWorld
{
class Hello {
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}

In this alternative version, using System; is added at the beginning, allowing for the simplification of
System.Console.WriteLine("Hello World!"); to Console.WriteLine("Hello World!"); for convenience.

Key Takeaways
Every C# program necessitates a class definition.

Program execution initiates from the Main() method.

The Main() method must reside within a class definition.

This basic program serves as an introduction to C#. As the tutorial progresses, concepts will become
clearer, making it accessible even for beginners.

C# Keywords and Identifiers

C# Keywords
Keywords in C# are predefined reserved words that carry specific meanings in a program and cannot be
altered. Attempting to use them as identifiers or changing their functions is prohibited. The C# language
comprises 79 keywords, all written in lowercase. Here is a comprehensive list of C# keywords:

abstract as base bool


break byte case catch
char checked class const
continue decimal default delegate
do double else enum
event explicit extern false
finally fixed float for
foreach goto if implicit
in in (generic modifier) int interface
internal is lock long

Complete Note Of Csharp(C#): 2


namespace new null object
operator out out (generic modifier) override
params private protected public
readonly ref return sbyte
sealed short sizeof stackalloc
static string struct switch
this throw true try
typeof uint ulong unchecked
unsafe ushort using using static
void volatile while

While keywords are reserved, the prefix "@" allows them to be used as identifiers. For instance:

int @void;

Contextual Keywords
In addition to regular keywords, C# features 25 contextual keywords. These words hold specific meanings
within certain program contexts but do not have reserved status across the entire language. Contextual
keywords include:

add alias ascending


async await descending
dynamic from get
global group into
join let orderby
partial (type) partial (method) remove
select set value
var when (filter condition) where (generic type constraint)
yield

For an in-depth understanding of each keyword, the official C# documentation can be referenced.

C# Identifiers
Identifiers serve as names for entities like variables, methods, and classes, uniquely identifying each
element in a program. However, certain rules govern their usage:

1. An identifier cannot be a C# keyword.

2. It must commence with a letter, underscore, or "@" symbol, followed by letters, digits, or underscores.

3. Whitespace and symbols other than letters, digits, and underscores are prohibited.

4. Identifiers are case-sensitive.

Examples of valid and invalid identifiers:

Valid:

number

calculateMarks

Complete Note Of Csharp(C#): 3


_hello_hi

Invalid:

hello$ (contains "$")

My name (contains whitespace)

if (C# keyword)

Example: Keywords and Identifiers in "Hello World!" Program

Keywords
using

namespace

class

static

void

string

Identifiers
System

HelloWorld (namespace)

Hello (class)

Main (method)

args

Console

WriteLine

The text "Hello World!" inside the WriteLine method is a string literal.

C# Variables and (Primitive) Data Types

Variables in C#
A variable in C# is a symbolic name assigned to a memory location, utilized for storing data within a
computer program. Declaration of a variable involves specifying its type and name. Here's an example:

int age;

In this case, a variable named age of type int (integer) is declared. It can later be assigned a value:

int age;
// ... ... ...
age = 24;

Alternatively, the variable can be initialized during declaration:

Complete Note Of Csharp(C#): 4


int age = 24;

Variables in C# must be declared before usage, adhering to the language's static typing nature.

Implicitly typed variables can be declared using the var keyword, where the compiler determines the type
based on the assigned value:

var value = 5;

Rules for Naming Variables in C#


1. The variable name can include letters (uppercase and lowercase), underscore (_), and digits.

2. It must start with a letter, underscore, or '@' symbol.

3. Whitespace and symbols other than letters, digits, and underscores are not allowed.

4. Identifiers are case-sensitive.

5. A variable name cannot be a C# keyword.

Best Practices for Naming a Variable


Choose meaningful variable names.

Use camelCase for local variables ( numberOfStudents , age ).

Use PascalCase or camelCase for public member variables ( FirstName , price ).

Prefix private member variables with a leading underscore ( _bankBalance , _emailAddress ).

C# Primitive Data Types

Boolean ( bool )
Represents true or false .

Default value: false .

Used for conditions in statements.

Example:

using System;
namespace DataType
{
class BooleanExample
{
public static void Main(string[] args)
{
bool isValid = true;
Console.WriteLine(isValid);
}
}
}

Complete Note Of Csharp(C#): 5


Output: True

Signed Integral
1. sbyte

Size: 8 bits

Range: -128 to 127

Default value: 0

Example:

using System;
namespace DataType
{
class SByteExample
{
public static void Main(string[] args)
{
sbyte level = 23;
Console.WriteLine(level);
}
}
}

Output: 23

2. short

Size: 16 bits

Range: -32,768 to 32,767

Default value: 0

Example:

using System;
namespace DataType
{
class ShortExample
{
public static void Main(string[] args)
{
short value = -1109;
Console.WriteLine(value);
}
}
}

Output: -1109

3. int

Complete Note Of Csharp(C#): 6


Size: 32 bits

Range: -2,147,483,648 to 2,147,483,647

Default value: 0

Example:

using System;
namespace DataType
{
class IntExample
{
public static void Main(string[] args)
{
int score = 51092;
Console.WriteLine(score);
}
}
}

Output: 51092

4. long

Size: 64 bits

Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Default value: 0L (L indicates long type)

Example:

using System;
namespace DataType
{
class LongExample
{
public static void Main(string[] args)
{
long range = -7091821871L;
Console.WriteLine(range);
}
}
}

Output: -7091821871

Unsigned Integral
1. byte

Size: 8 bits

Range: 0 to 255

Complete Note Of Csharp(C#): 7


Default value: 0

Example:

using System;
namespace DataType
{
class ByteExample
{
public static void Main(string[] args)
{
byte age = 62;
Console.WriteLine(age);
}
}
}

Output: 62

2. ushort

Size: 16 bits

Range: 0 to 65,535

Default value: 0

Example:

using System;
namespace DataType
{
class UShortExample
{
public static void Main(string[] args)
{
ushort value = 42019;
Console.WriteLine(value);
}
}
}

Output: 42019

3. uint

Size: 32 bits

Range: 0 to 4,294,967,295

Default value: 0

Example:

Complete Note Of Csharp(C#): 8


using System;
namespace DataType
{
class UIntExample
{
public static void Main(string[] args)
{
uint totalScore = 1151092;
Console.WriteLine(totalScore);
}
}
}

Output: 1151092

4. ulong

Size: 64 bits

Range: 0 to 18,446,744,073,709,551,615

Default value: 0

Example:

using System;
namespace DataType
{
class ULongExample
{
public static void Main(string[] args)
{
ulong range = 17091821871L;
Console.WriteLine(range);
}
}
}

Output: 17091821871

Floating Point
1. float

Size: 32 bits


Range: 1.5 × 10⁻ ⁵ to 3.4 × 10³⁸

Default value: 0.0F (F indicates float type)

Example:

using System;
namespace DataType

Complete Note Of Csharp(C#): 9


{
class FloatExample
{
public static void Main(string[] args)
{
float number = 43.27F;
Console.WriteLine(number);
}
}
}

Output: 43.27

2. double

Size: 64 bits


Range: 5.0 × 10⁻³² to 1.7 × 10³⁰⁸

Default value: 0.0D (D indicates double type)

Example:

using System;
namespace DataType
{
class DoubleExample
{
public static

void Main(string[] args)


{
double value = -11092.53D;
Console.WriteLine(value);
}
}
}

Output: `-11092.53`

##### Character (`char`)

- Represents a 16-bit Unicode character.


- Default value: `\\0` (null character)
- Range: U+0000 ('\\u0000') to U+FFFF ('\\uffff')

**Example:**
```csharp
using System;
namespace DataType

Complete Note Of Csharp(C#): 10


{
class CharExample
{
public static void Main(string[] args)
{
char ch1 = '\\u0042'; // Unicode 'B'
char ch2 = 'x';
Console.WriteLine(ch1);
Console.WriteLine(ch2);
}
}
}

Output:

B
x

Decimal
Size: 128 bits

Default value: 0.0M (M indicates decimal type)

Range: (-7.9 × 10²⁸ to 7.9 × 10²⁸) / (100 to 28)

Example:

using System;
namespace DataType
{
class DecimalExample
{
public static void Main(string[] args)
{
decimal bankBalance = 53005.25M;
Console.WriteLine(bankBalance);
}
}
}

Output: 53005.25

C# Literals
Literals are fixed values that appear directly in the program without computation.

Boolean Literals

true and false are boolean literals.

Used to initialize boolean variables.

Complete Note Of Csharp(C#): 11


Example:

bool isValid = true;


bool isPresent = false;

Integer Literals

Used to initialize variables of integer data types.

Suffixes 'L' or 'l' indicate long type.

Example:

long value1 = 4200910L;


long value2 = -10928190L;

Hexadecimal representation uses '0x'.

Floating Point Literals

Used to initialize variables of float and double data types.

Suffixes 'f', 'F' for float , 'd', 'D' for double .

May contain 'e' or 'E' for scientific notation.

Example:

double number = 24.67; // double by default


float value = -12.29F;
double scientificNotation = 6.21e2; // equivalent to 621

Character and String Literals

Character literals are enclosed in single quotes.

String literals are enclosed in double quotes.

Escape sequences are supported.

Example:

char ch1 = '\\u0042'; // Unicode 'B'


char ch2 = 'x';
string firstName = "Richard";
string lastName = " Feynman";

Escape sequence characters:

\\' : Single quote

\\" : Double quote

\\\\ : Backslash

\\n : Newline

\\r : Carriage return

Complete Note Of Csharp(C#): 12


\\t : Horizontal Tab

\\a : Alert

\\b : Backspace

C# Operators

1. Basic Assignment Operator


The basic assignment operator ( = ) in C# is utilized to assign values to variables. In the provided example:

double x;
x = 50.05;

Here, the value 50.05 is assigned to the variable x .

Example: Basic Assignment Operator

using System;

namespace Operator
{
class AssignmentOperator
{
public static void Main(string[] args)
{
int firstNumber, secondNumber;
// Assigning a constant to a variable
firstNumber = 10;
Console.WriteLine("First Number = {0}", firstNumber);

// Assigning a variable to another variable


secondNumber = firstNumber;
Console.WriteLine("Second Number = {0}", secondNumber);
}
}
}

Output:

First Number = 10
Second Number = 10

2. Arithmetic Operators
Arithmetic operators in C# perform operations such as addition, subtraction, multiplication, division, and
modulo (remainder). Example operations are:

int x = 5;
int y = 10;

Complete Note Of Csharp(C#): 13


int z = x + y; // z = 15

C# Arithmetic Operators:

+ : Addition Operator

: Subtraction Operator

: Multiplication Operator

/ : Division Operator

% : Modulo Operator (Remainder)

Example: Arithmetic Operators

using System;

namespace Operator
{
class ArithmeticOperator
{
public static void Main(string[] args)
{
double firstNumber = 14.40, secondNumber = 4.60, result;
int num1 = 26, num2 = 4, rem;

// Addition operator
result = firstNumber + secondNumber;
Console.WriteLine("{0} + {1} = {2}", firstNumber, secondNumber,
result);

// Subtraction operator
result = firstNumber - secondNumber;
Console.WriteLine("{0} - {1} = {2}", firstNumber, secondNumber,
result);

// Multiplication operator
result = firstNumber * secondNumber;
Console.WriteLine("{0} * {1} = {2}", firstNumber, secondNumber,
result);

// Division operator
result = firstNumber / secondNumber;
Console.WriteLine("{0} / {1} = {2}", firstNumber, secondNumber,
result);

// Modulo operator
rem = num1 % num2;
Console.WriteLine("{0} % {1} = {2}", num1, num2, rem);
}

Complete Note Of Csharp(C#): 14


}
}

Output:

14.4 + 4.6 = 19
14.4 - 4.6 = 9.8
14.4 * 4.6 = 66.24
14.4 / 4.6 = 3.1304347826087
26 % 4 = 2

3. Relational Operators
Relational operators check the relationship between two operands and result in either true or false.
Examples include:

bool result;
int firstNumber = 10, secondNumber = 20;

result = (firstNumber == secondNumber); // Equal to


result = (firstNumber > secondNumber); // Greater than
result = (firstNumber < secondNumber); // Less than
result = (firstNumber >= secondNumber); // Greater than or equal to
result = (firstNumber <= secondNumber); // Less than or equal to
result = (firstNumber != secondNumber); // Not equal to

C# Relational Operators:

== : Equal to

> : Greater than

< : Less than

>= : Greater than or equal to

<= : Less than or equal to

!= : Not equal to

Example: Relational Operators

using System;

namespace Operator
{
class RelationalOperator
{
public static void Main(string[] args)
{
bool result;
int firstNumber = 10, secondNumber = 20;

Complete Note Of Csharp(C#): 15


result = (firstNumber == secondNumber);
Console.WriteLine("{0} == {1} returns {2}", firstNumber, second
Number, result);

result = (firstNumber > secondNumber);


Console.WriteLine("{0} > {1} returns {2}", firstNumber, secondN
umber, result);

result = (firstNumber < secondNumber);


Console.WriteLine("{0} < {1} returns {2}", firstNumber, secondN
umber, result);

result = (firstNumber >= secondNumber);


Console.WriteLine("{0} >= {1} returns {2}", firstNumber, second
Number, result);

result = (firstNumber <= secondNumber);


Console.WriteLine("{0} <= {1} returns {2}", firstNumber, second
Number, result);

result = (firstNumber != secondNumber);


Console.WriteLine("{0} != {1} returns {2}", firstNumber, second
Number, result);
}
}
}

Output:

10 == 20 returns False
10 > 20 returns False
10 < 20 returns True
10 >= 20 returns False
10 <= 20 returns True
10 != 20 returns True

4. Logical Operators
Logical operators ( && for AND, || for OR) perform logical operations on boolean expressions, resulting in
boolean values. Example usage:

bool result;
int firstNumber = 10, secondNumber = 20;

// OR operator
result = (firstNumber == secondNumber) || (firstNumber > 5);

Complete Note Of Csharp(C#): 16


// AND operator
result = (firstNumber == secondNumber) && (firstNumber > 5);

C# Logical Operators:

&& : Logical AND

|| : Logical OR

! : Logical Negation (NOT)

Example: Logical Operators

using System;

namespace Operator
{
class LogicalOperator
{
public static void Main(string[] args)
{
bool result;
int firstNumber = 10, secondNumber = 20;

// OR operator
result = (firstNumber == secondNumber) || (firstNumber > 5);
Console.WriteLine(result);

// AND operator
result = (firstNumber == secondNumber) && (firstNumber > 5);
Console.WriteLine(result);
}
}
}

Output:

True
False

5. Unary Operators
Unary operators ( + , - , ++ , -- , ! ) operate on a single operand. Examples include:

int number = 10;


bool flag = true;

int result = +number; // Unary Plus


result = -number; // Unary Minus
result = ++number; // Increment

Complete Note Of Csharp(C#): 17


result = --number; // Decrement
bool negation = !flag; // Logical Negation (NOT)

C# Unary Operators:

+ : Unary Plus

: Unary Minus

++`: Increment

- : Decrement

! : Logical Negation (NOT)

Example: Unary Operators

using System;

namespace Operator
{
class UnaryOperator
{
public static void Main(string[] args)
{
int number = 10, result;
bool flag = true;

result = +number;
Console.WriteLine("+number = " + result);

result = -number;
Console.WriteLine("-number = " + result);

result = ++number;
Console.WriteLine("++number = " + result);

result = --number;
Console.WriteLine("--number = " + result);

Console.WriteLine("!flag = " + (!flag));


}
}
}

Output:

+number = 10
-number = -10
++number = 11

Complete Note Of Csharp(C#): 18


--number = 10
!flag = False

For further details on increment and decrement operators, refer to Example 6 in the provided code.

6. Ternary Operator
The ternary operator ( ? : ) in C# acts as a shorthand for an if-then-else statement. It is used in scenarios
where a decision needs to be made based on a condition. Example:

int number = 10;


string result = (number % 2 == 0) ? "Even Number" : "Odd Number";
Console.WriteLine("{0} is {1}", number, result);

Example: Ternary Operator

using System;

namespace Operator
{
class TernaryOperator
{
public static void Main(string[] args)
{
int number = 10;
string result = (number % 2 == 0) ? "Even Number" : "Odd Numbe
r";
Console.WriteLine("{0} is {1}", number, result);
}
}
}

Output:

10 is Even Number

7. Bitwise and Bit Shift Operators


Bitwise and bit shift operators ( ~ , & , | , ^ , << , >> ) are used for bit manipulation operations. Example
operations are:

int firstNumber = 10;


int secondNumber = 20;
int result;

result = ~firstNumber; // Bitwise Complement


result = firstNumber & secondNumber; // Bitwise AND
result = firstNumber | secondNumber; // Bitwise OR
result = firstNumber ^ secondNumber; // Bitwise Exclusive OR

Complete Note Of Csharp(C#): 19


result = firstNumber << 2; // Bitwise Left Shift
result = firstNumber >> 2; // Bitwise Right Shift

C# Bitwise and Bit Shift Operators:

~ : Bitwise Complement

& : Bitwise AND

| : Bitwise OR

^ : Bitwise Exclusive OR

<< : Bitwise Left Shift

>> : Bitwise Right Shift

Example: Bitwise and Bit Shift Operator

using System;

namespace Operator
{
class BitOperator
{
public static void Main(string[] args)
{
int firstNumber = 10;
int secondNumber = 20;
int result;

result = ~firstNumber;
Console.WriteLine("~{0} = {1}", firstNumber, result);

result = firstNumber & secondNumber;


Console.WriteLine("{0} & {1} = {2}", firstNumber,secondNumber,
result);

result = firstNumber | secondNumber;


Console.WriteLine("{0} | {1} = {2}", firstNumber,secondNumber,
result);

result = firstNumber ^ secondNumber;


Console.WriteLine("{0} ^ {1} = {2}", firstNumber,secondNumber,
result);

result = firstNumber << 2;


Console.WriteLine("{0} << 2 = {1}", firstNumber, result);

result = firstNumber >> 2;


Console.WriteLine("{0} >> 2 = {1}", firstNumber, result);
}

Complete Note Of Csharp(C#): 20


}
}

Output:

~10 = -11
10 & 20 = 0
10 | 20 = 30
10 ^ 20 = 30
10 << 2 = 40
10 >> 2 = 2

8. Compound Assignment Operators


Compound assignment operators ( += , -= , *= , /= , %= , &= , |= , ^= , <<= , >>= ) combine an arithmetic
operation with assignment. Example usage:

int number = 10;

number += 5; // Addition Assignment (x += 5 is equivalent to x = x + 5)


number -= 3; // Subtraction Assignment (x -= 3 is equivalent to x = x -
3)
number *= 2; // Multiplication Assignment (x *= 2 is equivalent to x = x
* 2)
number /= 3; // Division Assignment (x /= 3 is equivalent to x = x / 3)
number %= 3; // Modulo Assignment (x %= 3 is equivalent to x = x % 3)
number &= 10; // Bitwise AND Assignment (x &= 10 is equivalent to x = x &
10)
number |= 14; // Bitwise OR Assignment (x |= 14 is equivalent to x = x | 1
4)
number ^= 12; // Bitwise XOR Assignment (x ^= 12 is equivalent to x = x ^
12)
number <<= 2; // Left Shift Assignment (x <<= 2 is equivalent to x = x <<
2)
number >>= 3; // Right Shift Assignment (x >>= 3 is equivalent to x = x >>
3)

C# Compound Assignment Operators:

+= : Addition Assignment

= : Subtraction Assignment

= : Multiplication Assignment

/= : Division Assignment

%= : Modulo Assignment

&= : Bitwise AND Assignment

|= : Bitwise OR Assignment

Complete Note Of Csharp(C#): 21


^= : Bitwise XOR Assignment

<<= : Left Shift Assignment

>>= : Right Shift Assignment

Example: Compound Assignment Operator

using System;

namespace Operator
{
class BitOperator
{
public static void Main(string[] args)
{
int number = 10;

number += 5;
Console.WriteLine(number);

number -= 3;
Console.WriteLine(number);

number *= 2;
Console.WriteLine(number);

number /= 3;
Console.WriteLine(number);

number %= 3;
Console.WriteLine(number);

number &= 10;


Console.WriteLine(number);

number |= 14;
Console.WriteLine(number);

number ^= 12;
Console.WriteLine(number);

number <<= 2;
Console.WriteLine(number);

number >>= 3;
Console.WriteLine(number);
}

Complete Note Of Csharp(C#): 22


}
}

Output:

15
12
24
8
2
2
14
2
8
1

The provided examples cover a comprehensive overview of various operators in C#, aiding in arithmetic

C# Operator Precedence and Associativity


Operator Precedence
In C#, operator precedence determines the order in which operations are carried out within an expression.
Each operator is assigned a priority, and expressions are evaluated based on these priorities. The higher
the precedence of an operator, the earlier it is evaluated.

Example: Operator Precedence

using System;

namespace Operator
{
class OperatorPrecedence
{
public static void Main(string[] args)
{
int result1;
int a = 5, b = 6, c = 4;
result1 = --a * b - ++c;
Console.WriteLine(result1);

bool result2;
result2 = b >= c + a;
Console.WriteLine(result2);
}
}
}

Output:

Complete Note Of Csharp(C#): 23


19
False

Explanation:

1. For the expression result1 = --a * b - ++c; , the operators - and ++ have higher precedence than
and . The expression is equivalent to result1 = ((--a) * b) - (++c) .

-a is evaluated first, resulting in a being decremented to 4.

++c is then evaluated, resulting in c being incremented to 5.

The multiplication 4 * b is calculated, yielding 24.

Finally, the subtraction 24 - 5 is performed, resulting in result1 being 19.

2. For the expression result2 = b >= c + a; , the precedence of + is higher than >= . Thus, c + a is
calculated first, resulting in 9. The comparison b >= 9 is evaluated, yielding False .

Operator Precedence Table


The following table outlines the operator precedence in C#:

C# Operator Precedence

Category Operators
-------------------------------------------
Postfix Increment and Decrement ++, --
Prefix Increment, Decrement, Unary ++, --, +, -, !, ~
Multiplicative *, /, %
Additive +, -
Shift <<, >>
Relational <, <=, >, >=
Equality ==, !=
Bitwise AND &
Bitwise XOR ^
Bitwise OR |
Logical AND &&
Logical OR ||
Ternary ? :
Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

Associativity of Operators in C#
When operators of the same precedence appear in an expression, the associativity of the operators
determines the order of evaluation. In C#, most operators have left-to-right associativity.

Example: Associativity of Operators

using System;

namespace Operator
{

Complete Note Of Csharp(C#): 24


class OperatorPrecedence
{
public static void Main(string[] args)
{
int a = 5, b = 6, c = 3;
int result = a * b / c;
Console.WriteLine(result);

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

Output:

10
a = 3, b = 3, c = 3

Explanation:

1. For the expression result = a * b / c; , the operators and / have the same precedence, but their
associativity is left-to-right. Therefore, a * b is evaluated first, resulting in 30, and then 30 / c is
calculated, yielding result as 10.

2. For the expression a = b = c; , the assignment operator = has right-to-left associativity. The value of
c (3) is assigned to b , and then the value of b is assigned to a . After this statement, the values of
a , b , and c are all 3.

C# Bitwise and Bit Shift Operators


Bitwise Operators
Bitwise and bit shift operators in C# are utilized for performing bit-level operations on integer (int, long,
etc.) and boolean data types. Although these operators are not commonly used in practical scenarios, they
find applications in certain specialized contexts.

List of C# Bitwise Operators


Operator Operator Name

~ Bitwise Complement

& Bitwise AND

| Bitwise OR

^ Bitwise Exclusive OR (XOR)

<< Bitwise Left Shift

>> Bitwise Right Shift

Bitwise OR Operator ( | )

Complete Note Of Csharp(C#): 25


The Bitwise OR operator ( | ) performs a bitwise OR operation on corresponding bits of two operands. If
either of the bits is 1, the result is 1; otherwise, the result is 0.
Example 1: Bitwise OR

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

Output:

14 | 11 = 15

Bitwise AND Operator ( & )


The Bitwise AND operator ( & ) performs a bitwise AND operation on corresponding bits of two operands. If
either of the bits is 0, the result is 0; otherwise, the result is 1.

Example 2: Bitwise AND

using System;

namespace Operator
{
class BitWiseAND
{
public static void Main(string[] args)
{
int firstNumber = 14, secondNumber = 11, result;
result = firstNumber & secondNumber;
Console.WriteLine("{0} & {1} = {2}", firstNumber, secondNumber,
result);
}
}
}

Output:

Complete Note Of Csharp(C#): 26


14 & 11 = 10

Bitwise XOR Operator ( ^ )


The Bitwise XOR operator ( ^ ) performs a bitwise XOR operation on corresponding bits of two operands.
If the corresponding bits are the same, the result is 0; if they are different, the result is 1.
Example 3: Bitwise XOR

using System;

namespace Operator
{
class BitWiseXOR
{
public static void Main(string[] args)
{
int firstNumber = 14, secondNumber = 11, result;
result = firstNumber ^ secondNumber;
Console.WriteLine("{0} ^ {1} = {2}", firstNumber, secondNumber,
result);
}
}
}

Output:

14 ^ 11 = 5

Bitwise Complement Operator ( ~ )


The Bitwise Complement operator ( ~ ) is a unary operator that inverts each bit of its operand, changing 1s
to 0s and 0s to 1s.
Example 4: Bitwise Complement

using System;

namespace Operator
{
class BitWiseComplement
{
public static void Main(string[] args)
{
int number = 26, result;
result = ~number;
Console.WriteLine("~{0} = {1}", number, result);
}

Complete Note Of Csharp(C#): 27


}
}

Output:

~26 = -27

Note: The output is in 2's complement representation.

Bitwise Left Shift Operator ( << )


The Bitwise Left Shift operator ( << ) shifts the bits of a number to the left by a specified number of
positions, adding zeroes to the least significant bits.

Example 5: Bitwise Left Shift

using System;

namespace Operator
{
class LeftShift
{
public static void Main(string[] args)
{
int number = 42;

Console.WriteLine("{0}<<1 = {1}", number, number << 1);


Console.WriteLine("{0}<<2 = {1}", number, number << 2);
Console.WriteLine("{0}<<4 = {1}", number, number << 4);
}
}
}

Output:

42<<1 = 84
42<<2 = 168
42<<4 = 672

Bitwise Right Shift Operator ( >> )


The Bitwise Right Shift operator ( >> ) shifts the bits of a number to the right by a specified number of
positions, using sign extension for signed integers.
Example 6: Bitwise Right Shift

using System;

namespace Operator
{

Complete Note Of Csharp(C#): 28


class RightShift
{
public static void Main(string[] args)
{
int number = 42;

Console.WriteLine("{0}>>1 = {1}", number, number >> 1);


Console.WriteLine("{0}>>2 = {1}", number, number >> 2);
Console.WriteLine("{0}>>4 = {1}", number, number >> 4);
}
}
}

Output:

42>>1 = 21
42>>2 = 10
42>>4 = 2

C# Basic Input and Output


C# Output
In C#, output is facilitated through the Console class, offering two primary methods for displaying content:

1. System.Console.WriteLine()

2. System.Console.Write()

In these methods, System is the namespace, Console is a class within the System namespace, and
WriteLine and Write are methods of the Console class.

Example 1: Printing String using WriteLine()

using System;

namespace Sample
{
class Test
{
public static void Main(string[] args)
{
Console.WriteLine("C# is cool");
}
}
}

Output:

Complete Note Of Csharp(C#): 29


C# is cool

Difference between WriteLine() and Write() Method


The key distinction between WriteLine() and Write() is that Write() only prints the provided string, while
WriteLine() also moves to the start of the next line.

Example 2: Using WriteLine() and Write()

using System;

namespace Sample
{
class Test
{
public static void Main(string[] args)
{
Console.WriteLine("Prints on ");
Console.WriteLine("New line");

Console.Write("Prints on ");
Console.Write("Same line");
}
}
}

Output:

Prints on
New line
Prints on Same line

Printing Variables and Literals using WriteLine() and Write()


Variables and literals can be printed using these methods:

Example 3: Printing Variables and Literals

using System;

namespace Sample
{
class Test
{
public static void Main(string[] args)
{
int value = 10;

Complete Note Of Csharp(C#): 30


// Variable
Console.WriteLine(value);
// Literal
Console.WriteLine(50.05);
}
}
}

Output:

10
50.05

Combining (Concatenating) two strings using + operator and printing them


Strings can be concatenated using the + operator:

Example 4: Concatenating Strings using + Operator

using System;

namespace Sample
{
class Test
{
public static void Main(string[] args)
{
int val = 55;
Console.WriteLine("Hello " + "World");
Console.WriteLine("Value = " + val);
}
}
}

Output:

Hello World
Value = 55

Printing Concatenated String using Formatted String [Better Alternative]


A better alternative for concatenating strings is using formatted strings, providing better readability and
avoiding errors:

Example 5: Concatenating Strings using Formatted String

using System;

namespace Sample

Complete Note Of Csharp(C#): 31


{
class Test
{
public static void Main(string[] args)
{
int firstNumber = 5, secondNumber = 10, result;
result = firstNumber + secondNumber;
Console.WriteLine("{0} + {1} = {2}", firstNumber, secondNumber,
result);
}
}
}

Output:

5 + 10 = 15

C# Input
In C#, user input is commonly obtained using the ReadLine() method of the Console class. Additionally,
Read() and ReadKey() methods are available for different input scenarios.

Example 6: Get String Input From User

using System;

namespace Sample
{
class Test
{
public static void Main(string[] args)
{
string testString;
Console.Write("Enter a string - ");
testString = Console.ReadLine();
Console.WriteLine("You entered '{0}'", testString);
}
}
}

Output:

Enter a string - Hello World


You entered 'Hello World'

Difference between ReadLine() , Read() , and ReadKey() method


The difference between ReadLine() , Read() , and ReadKey() methods lies in their behavior:

Complete Note Of Csharp(C#): 32


ReadLine() : Reads the next line of input from the standard input stream and returns the same string.

Read() : Reads the next character from the standard input stream and returns the ASCII value of the
character.

ReadKey() : Obtains the next key pressed by the user and is typically used to wait for a key press.

Example 7: Difference between Read() and ReadKey() method

using System;

namespace Sample
{
class Test
{
public static void Main(string[] args)
{
int userInput;

Console.WriteLine("Press any key to continue...");


Console.ReadKey();
Console.WriteLine();

Console.Write("Input using Read() - ");


userInput = Console.Read();
Console.WriteLine("Ascii Value = {0}",userInput);
}
}
}

Output:

Press any key to continue...


x
Input using Read() - Learning C#
Ascii Value = 76

Reading Numeric Values (integer and floating point types)


Reading numeric values involves using the ReadLine() method to receive input as a string and then
converting it to the desired type, often utilizing the methods of the Convert class.

Example 8: Reading Numeric Values from User using Convert class

using System;

namespace UserInput
{
class MyClass
{

Complete Note Of Csharp(C#): 33


public static void Main(string[] args)
{
string userInput;
int intVal;
double doubleVal;

Console.Write("Enter integer value: ");


userInput = Console.ReadLine();
/* Converts to integer type */
intVal = Convert.ToInt32(userInput);
Console.WriteLine("You entered {0}",intVal);

Console.Write("Enter double value: ");


userInput = Console.ReadLine();
/* Converts to double type */
doubleVal = Convert.ToDouble(userInput);
Console.WriteLine("You entered {0}",doubleVal);
}
}
}

Output:

Enter integer value: 101


You entered 101
Enter double value: 59.412
You entered 59.412

In this example, ToInt32() and ToDouble() methods of the Convert class are used to convert the string
input to integer and double types, respectively.

C# Expressions, Statements, and Blocks

C# Expressions
Expressions in C# are combinations of operands (variables, literals, method calls) and operators that
evaluate to a single value. An expression must have at least one operand, but it may not necessarily
include an operator.

Example 1:

double temperature;
temperature = 42.05;

Here, 42.05 is an expression, and temperature = 42.05 is also an expression.

int a, b, c, sum;
sum = a + b + c;

Complete Note Of Csharp(C#): 34


In this example, a + b + c is an expression.

if (age >= 18 && age < 58)


Console.WriteLine("Eligible to work");

Here, (age >= 18 && age < 58) is an expression that returns a boolean value. "Eligible to work" is also an
expression.

C# Statements
A statement is a basic unit of program execution, and a program consists of multiple statements. There are
different types of statements in C#, and we'll focus on two main types in this tutorial: declaration
statements and expression statements.

Declaration Statement
Declaration statements are used to declare and initialize variables.

char ch;
int maxValue = 55;

Both char ch; and int maxValue = 55; are declaration statements.

Expression Statement
An expression followed by a semicolon is called an expression statement.

/* Assignment */
area = 3.14 * radius * radius;
/* Method call is an expression */
System.Console.WriteLine("Hello");

Here, 3.14 * radius * radius is an expression, and area = 3.14 * radius * radius; is an expression
statement. Similarly, System.Console.WriteLine("Hello"); is both an expression and a statement.
Besides declaration and expression statements, there are:

Selection Statements (if...else, switch)

Iteration Statements (do, while, for, foreach)

Jump Statements (break, continue, goto, return, yield)

Exception Handling Statements (throw, try-catch, try-finally, try-catch-finally)

These statements will be discussed in later tutorials.

C# Blocks
A block is a combination of zero or more statements enclosed inside curly brackets { } .

Example 1: C# Blocks with Statements

Complete Note Of Csharp(C#): 35


using System;

namespace Blocks
{
class BlockExample
{
public static void Main(string[] args)
{
double temperature = 42.05;
if (temperature > 32)
{ // Start of block
Console.WriteLine("Current temperature = {0}", temperatur
e);
Console.WriteLine("It's hot");
} // End of block
}
}
}

Output:

Current temperature = 42.05


It's hot

In this example, the two statements inside { } form a block.

Example 2: C# Blocks without Statements


A block may not have any statements within it.

using System;

namespace Blocks
{
class BlockExample
{
public static void Main(string[] args)
{
double temperature = 42.05;
if (temperature > 32)
{ // Start of block
// No statements
} // End of block
}
}
}

Here, the curly braces { } after if(temperature > 32) contain only comments and no statements.

Complete Note Of Csharp(C#): 36


C# Comments
Comments in a program serve the purpose of enhancing code readability and understanding. There are
three types of comments in C#:

Single Line Comments ( // )


Single-line comments start with a double slash // . The compiler ignores everything after // to the end of
the line.

Example 1: Using Single Line Comment

// Hello World Program


using System;

namespace HelloWorld
{
class Program
{
public static void Main(string[] args) // Execution Starts from Ma
in method
{
// Prints Hello World
Console.WriteLine("Hello World!");
}
}
}

The program contains three single-line comments:

// Hello World Program

// Execution Starts from Main method

// Prints Hello World

Multi Line Comments ( /* */ )


Multi-line comments start with /* and end with */ . They can span over multiple lines.

Example 2: Using Multi Line Comment

/*
This is a Hello World Program in C#.
This program prints Hello World.
*/
using System;

namespace HelloWorld
{
class Program
{

Complete Note Of Csharp(C#): 37


public static void Main(string[] args)
{
/* Prints Hello World */
Console.WriteLine("Hello World!");
}
}
}

The program contains two multi-line comments:

/* This is a Hello World Program in C#. This program prints Hello World. */

/* Prints Hello World */

XML Documentation Comments ( /// )


XML documentation comments start with /// and use XML tags to describe a piece of code. These
comments are used to generate a separate XML documentation file.

Example 3: Using XML Documentation Comment

/// <summary>
/// This is a hello world program.
/// </summary>
using System;

namespace HelloWorld
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}

The XML documentation comment used in the above program is /// <summary> This is a hello world

program. </summary> .
Comments should be used judiciously:

Avoid unnecessary comments for obvious code.

Use comments to explain complex algorithms or techniques.

Keep comments short and to the point.

Explain "why" instead of "how" when using comments.

Flow Control

Complete Note Of Csharp(C#): 38


C# if, if...else, if...else if, and Nested if Statement
Testing conditions is fundamental in programming, allowing the control flow of a program to adapt based
on various factors. In C#, conditional statements such as if, if...else, if...else if, and nested if statements
provide the means to execute different blocks of code based on specified conditions.

C# if Statement
The if statement in C# executes a block of code if the given condition is true. The syntax is as follows:

if (boolean-expression)
{
// statements executed if boolean-expression is true
}

The boolean-expression returns either true or false.

If true, the statements inside the if block will be executed.

If false, the statements inside the if block will be ignored.

Example 1: C# if Statement

using System;

namespace Conditional
{
class IfStatement
{
public static void Main(string[] args)
{
int number = 2;
if (number < 5)
{
Console.WriteLine("{0} is less than 5", number);
}

Console.WriteLine("This statement is always executed.");


}
}
}

Output:

2 is less than 5
This statement is always executed.

Explanation: The code inside the if block is executed because the value of number is less than 5.

C# if...else Statement

Complete Note Of Csharp(C#): 39


The if statement may have an optional else statement. The block inside the else statement is executed
if the expression is evaluated to false.

Example 2: C# if...else Statement

using System;

namespace Conditional
{
class IfElseStatement
{
public static void Main(string[] args)
{
int number = 12;

if (number < 5)
{
Console.WriteLine("{0} is less than 5", number);
}
else
{
Console.WriteLine("{0} is greater than or equal to 5", numb
er);
}

Console.WriteLine("This statement is always executed.");


}
}
}

Output:

12 is greater than or equal to 5


This statement is always executed.

Explanation: The code inside the else block is executed as the value of number is greater than or equal to
5.

C# if...else if Statement
The if...else if statement allows testing multiple conditions in sequence. The block of code associated
with the first true condition is executed.

Example 3: C# if...else if Statement

using System;

namespace Conditional
{

Complete Note Of Csharp(C#): 40


class IfElseIfStatement
{
public static void Main(string[] args)
{
int number = 12;

if (number < 5)
{
Console.WriteLine("{0} is less than 5", number);
}
else if (number > 5)
{
Console.WriteLine("{0} is greater than 5", number);
}
else
{
Console.WriteLine("{0} is equal to 5");
}
}
}
}

Output:

12 is greater than 5

Explanation: The code inside the else if block is executed as the first condition is false, and the second
condition is true.

Nested if...else Statement


A nested if...else statement involves placing one if...else statement inside another. It is useful for
testing one condition followed by another.

Example 4: Nested if...else Statement

using System;

namespace Conditional
{
class Nested
{
public static void Main(string[] args)
{
int first = 7, second = -23, third = 13;
if (first > second)
{
if (first > third)
{

Complete Note Of Csharp(C#): 41


Console.WriteLine("{0} is the largest", first);
}
else
{
Console.WriteLine("{0} is the largest", third);
}
}
else
{
if (second > third)
{
Console.WriteLine("{0} is the largest", second);
}
else
{
Console.WriteLine("{0} is the largest", third);
}
}
}
}
}

Output:

13 is the largest

Explanation: The program finds the largest among three numbers using nested if...else statements. In this
case, 13 is the largest.

C# switch Statement
The switch statement in C# serves as an alternative to the if...else if statement, providing cleaner and
more readable code. This statement is particularly advantageous when dealing with multiple conditions.

Syntax of switch Statement:


switch (variable/expression)
{
case value1:
// Statements executed if variable/expression equals value1
break;
case value2:
// Statements executed if variable/expression equals value2
break;
// ... ... ...
// ... ... ...
default:

Complete Note Of Csharp(C#): 42


// Statements executed if none of the cases match
}

The switch statement evaluates the expression or variable and compares its value with the values
listed in each case.

When a matching value is found, the statements inside that case are executed.

If none of the cases match, the statements inside the default block are executed.

Note: The break statement is crucial to terminate the execution of the switch statement once a match is
found. Without break , it would execute all statements until the end of the switch block.

Example 1: C# switch Statement

using System;

namespace Conditional
{
class SwitchCase
{
public static void Main(string[] args)
{
char ch;
Console.WriteLine("Enter an alphabet");
ch = Convert.ToChar(Console.ReadLine());

switch (Char.ToLower(ch))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
Console.WriteLine("Vowel");
break;
default:
Console.WriteLine("Not a vowel");
break;
}
}
}
}

Output:

Enter an alphabet
X
Not a vowel

Complete Note Of Csharp(C#): 43


Explanation: The program prompts the user to enter an alphabet, converts it to lowercase, and then
checks if it is a vowel using the switch statement.

Example 2: Simple calculator program using C# switch Statement

using System;

namespace Conditional
{
class SwitchCase
{
public static void Main(string[] args)
{
char op;
double first, second, result;

Console.Write("Enter first number: ");


first = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter second number: ");
second = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter operator (+, -, *, /): ");
op = (char)Console.Read();

switch (op)
{
case '+':
result = first + second;
Console.WriteLine("{0} + {1} = {2}", first, second, res
ult);
break;
case '-':
result = first - second;
Console.WriteLine("{0} - {1} = {2}", first, second, res
ult);
break;
case '*':
result = first * second;
Console.WriteLine("{0} * {1} = {2}", first, second, res
ult);
break;
case '/':
result = first / second;
Console.WriteLine("{0} / {1} = {2}", first, second, res
ult);
break;
default:
Console.WriteLine("Invalid Operator");
break;

Complete Note Of Csharp(C#): 44


}
}
}
}

Output:

Enter first number: -13.11


Enter second number: 2.41
Enter operator (+, -, *, /): *
-13.11 * 2.41 = -31.5951

Explanation: This program performs basic arithmetic operations based on user input using the switch

statement.
In summary, the switch statement in C# is a valuable tool for simplifying decision-making structures,
especially when dealing with multiple conditions. It enhances code readability and can be a powerful asset
in scenarios where it is applicable.

C# Ternary Operator
The ternary operator in C# serves as a concise alternative to the traditional if...else statement. Its syntax
is as follows:

Condition ? Expression1 : Expression2;

Here's how the ternary operator operates:

If the condition is true, the result of Expression1 is returned.

If the condition is false, the result of Expression2 is returned.

Example: C# Ternary Operator

using System;

namespace Conditional
{
class Ternary
{
public static void Main(string[] args)
{
int number = 2;
bool isEven;

isEven = (number % 2 == 0) ? true : false;


Console.WriteLine(isEven);
}

Complete Note Of Csharp(C#): 45


}
}

Output:

True

Explanation: In this example, the program checks if the variable number is even using the ternary operator.
Since 2 is even, the expression (number % 2 == 0) evaluates to true, and the result true is assigned to the
variable isEven .

It's worth noting that the ternary operator can be used to return various types, including numbers, strings,
and characters.

When to Use Ternary Operator?


The ternary operator is a powerful tool for simplifying code and reducing multiple lines into a single line.
However, it should be used judiciously. Here are some considerations:

Simplicity: Use the ternary operator to replace simple if...else statements and improve code
simplicity.

Readability: Avoid overusing the ternary operator, as it may decrease code readability, making it
challenging to understand the logic.

Complexity: For complex conditions and multiple branches, sticking with if...else statements may
enhance code clarity.

Example: Replacing if...else if with Ternary Operator

using System;

namespace Conditional
{
class Ternary
{
public static void Main(string[] args)
{
int a = 5, b = 10;
string result;

result = a > b ? "a is greater than b" : a < b ? "b is greater


than a" : "a is equal to b";
Console.WriteLine(result);
}
}
}

Output:

b is greater than a

Complete Note Of Csharp(C#): 46


Explanation: In this example, the program uses the ternary operator to replace an if...else if statement,
determining the relationship between variables a and b .
In conclusion, the ternary operator is a valuable tool for improving code conciseness, but it should be
employed thoughtfully to maintain code readability and understanding.

C# For Loop
In programming, the need to execute a block of statements for a specified number of times is common.
Loops are employed to repeatedly execute a certain block of statements until a specified condition is met.
In C#, the for loop is utilized for this purpose.

C# for Loop
The for keyword is used to create a for loop in C#. The syntax is as follows:

for (initialization; condition; iterator)


{
// body of the for loop
}

How for Loop Works


C# for loop consists of three statements: initialization, condition, and iterator.

1. The initialization statement is executed once, initializing a variable.

2. The condition is evaluated, returning either true or false.

3. If the condition is true, the statements inside the loop are executed. Then, the iterator statement is
executed, typically changing the initialized variable's value. The loop continues until the condition is
false.

4. If the condition is false, the for loop terminates.

Example 1: C# for Loop

using System;

namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("C# For Loop: Iteration {0}", i);
}
}

Complete Note Of Csharp(C#): 47


}
}

Output:

C# For Loop: Iteration 1


C# For Loop: Iteration 2
C# For Loop: Iteration 3
C# For Loop: Iteration 4
C# For Loop: Iteration 5

In this program, i is initialized to 1, and the loop continues until i is no longer less than or equal to 5.

Example 2: Sum of First n Natural Numbers

using System;

namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
int n = 5, sum = 0;

for (int i = 1; i <= n; i++)


{
sum += i;
}

Console.WriteLine("Sum of first {0} natural numbers = {1}", n,


sum);
}
}
}

Output:

Sum of first 5 natural numbers = 15

Here, the loop is used to compute the sum of the first n natural numbers.

Example 3: for Loop with Multiple Initialization and Iterator Expressions

using System;

namespace Loop
{

Complete Note Of Csharp(C#): 48


class ForLoop
{
public static void Main(string[] args)
{
for (int i = 0, j = 0; i + j <= 5; i++, j++)
{
Console.WriteLine("i = {0} and j = {1}", i, j);
}
}
}
}

Output:

i = 0 and j = 0
i = 1 and j = 1
i = 2 and j = 2

In this program, multiple variables are declared and initialized in the initialization statement, and both i

and j are incremented in the iterator part.

Example 4: for Loop without Initialization and Iterator Statements

using System;

namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
int i = 1;
for (; i <= 5;)
{
Console.WriteLine("C# For Loop: Iteration {0}", i);
i++;
}
}
}
}

Output:

C# For Loop: Iteration 1


C# For Loop: Iteration 2
C# For Loop: Iteration 3

Complete Note Of Csharp(C#): 49


C# For Loop: Iteration 4
C# For Loop: Iteration 5

In this example, the initialization and iterator statements are omitted, and the loop still functions as
expected.

Example 5: Infinite for Loop

using System;

namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
for (int i = 1; i > 0; i++)
{
Console.WriteLine("C# For Loop: Iteration {0}", i);
}
}
}
}

In this program, an infinite for loop is created where the condition is always true.
It's important to note that the initialization, condition, and iterator statements are optional in a for loop,
and when omitted, the loop serves as a while loop. However, caution should be exercised to avoid infinite
loops by ensuring that the condition eventually becomes false.

C# While Loop and Do...While Loop


In programming, loops are essential for executing a certain block of statements repeatedly. One common
scenario is when the number of repetitions is not known in advance. In C#, we have two primary loop
constructs: the while loop and the do...while loop.

C# While Loop
The while keyword is used to create a while loop in C#. The syntax is as follows:

while (test-expression)
{
// body of while loop
}

How while Loop Works


The while loop consists of a test-expression. The loop works as follows:

1. If the test-expression is true, the statements inside the while loop are executed.

Complete Note Of Csharp(C#): 50


2. After execution, the test-expression is evaluated again.

3. If the test-expression is evaluated to false, the while loop terminates.

Example 1: C# while Loop

using System;

namespace Loop
{
class WhileLoop
{
public static void Main(string[] args)
{
int i = 1;
while (i <= 5)
{
Console.WriteLine("C# While Loop: Iteration {0}", i);
i++;
}
}
}
}

Output:

C# While Loop: Iteration 1


C# While Loop: Iteration 2
C# While Loop: Iteration 3
C# While Loop: Iteration 4
C# While Loop: Iteration 5

In this program, the loop executes until the value of i becomes 6. The test-expression i <= 5 ensures
the loop runs as long as i is less than or equal to 5.

Example 2: while Loop to Compute Sum of First 5 Natural Numbers

using System;

namespace Loop
{
class WhileLoop
{
public static void Main(string[] args)
{
int i = 1, sum = 0;

while (i <= 5)
{

Complete Note Of Csharp(C#): 51


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

Output:

Sum = 15

This program computes the sum of the first 5 natural numbers using a while loop.

C# Do...While Loop
The and while keywords are used to create a do...while loop. In contrast to the
do while loop, the
do...while loop executes the body first and then checks the test-expression.

The syntax for the do...while loop is:

do
{
// body of do while loop
} while (test-expression);

How do...while Loop Works


1. The body of the do...while loop is executed first.

2. Then, the test-expression is evaluated.

3. If the test-expression is true, the body of the loop is executed again.

4. When the test-expression is false, the do...while loop terminates.

Example 3: C# do...while Loop

using System;

namespace Loop
{
class DoWhileLoop
{
public static void Main(string[] args)
{
int i = 1, n = 5, product;

do
{
product = n * i;

Complete Note Of Csharp(C#): 52


Console.WriteLine("{0} * {1} = {2}", n, i, product);
i++;
} while (i <= 10);
}
}
}

Output:

5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

This program prints the multiplication table of the number 5 using a do...while loop. The loop runs at least
once, irrespective of the test-expression.

Infinite while and do...while Loop


An infinite loop occurs when the test expression never evaluates to false, causing the loop to run
indefinitely. This is useful in scenarios where continuous execution is required.
For example:

Infinite while Loop

while (true)
{
// body of while loop
}

Infinite do...while Loop

do
{
// body of while loop
} while (true);

It's crucial to exercise caution with infinite loops to prevent unintended consequences and ensure the loop
is terminated appropriately in your program.

C# Nested Loops: for, while, do-while

Complete Note Of Csharp(C#): 53


In C#, a loop within another loop is referred to as a nested loop. The structure of a nested loop involves an
outer loop containing an inner loop. The inner loop is executed within the body of the outer loop and must
start and finish within the outer loop's body.

Nested For Loop


A for loop inside another for loop is known as a nested for loop. The syntax is as follows:

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


{
// body of outer for loop
for (int j = 0; j < 5; j++)
{
// body of inner for loop
}
// body of outer for loop
}

Example 1: Nested For Loop

using System;

namespace Loop
{
class NestedForLoop
{
public static void Main(string[] args)
{
int outerLoop = 0, innerLoop = 0;
for (int i = 1; i <= 5; i++)
{
outerLoop++;
for (int j = 1; j <= 5; j++)
{
innerLoop++;
}
}
Console.WriteLine("Outer Loop runs {0} times", outerLoop);
Console.WriteLine("Inner Loop runs {0} times", innerLoop);
}
}
}

Output:

Outer Loop runs 5 times


Inner Loop runs 25 times

Complete Note Of Csharp(C#): 54


In this program, the outer loop runs 5 times, and for each iteration of the outer loop, the inner loop runs 5
times, resulting in a total of 25 iterations.

Example 2: Nested For Loop to Print Pattern

using System;

namespace Loop
{
class NestedForLoop
{
public static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write(j + " ");
}
Console.WriteLine();
}
}
}
}

Output:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

This program prints a pattern using a nested for loop.

Nested While Loop


A while loop inside another while loop is termed a nested while loop. The syntax is as follows:

while (condition-1)
{
// body of outer while loop
while (condition-2)
{
// body of inner while loop
}
// body of outer while loop
}

Complete Note Of Csharp(C#): 55


Example 3: Nested While Loop

using System;

namespace Loop
{
class NestedWhileLoop
{
public static void Main(string[] args)
{
int i = 0;
while (i < 2)
{
int j = 0;
while (j < 2)
{
Console.Write("({0},{1}) ", i, j);
j++;
}
i++;
Console.WriteLine();
}
}
}
}

Output:

(0,0) (0,1)
(1,0) (1,1)

This program demonstrates the usage of nested while loops to print pairs of numbers.

Nested Do-While Loop


A do-while loop inside another do-while loop is known as a nested do-while loop. The syntax is as follows:

do
{
// body of outer do-while loop
do
{
// body of inner do-while loop
} while (condition-2);
// body of outer do-while loop
} while (condition-1);

Example 4: Nested Do-While Loop

Complete Note Of Csharp(C#): 56


using System;

namespace Loop
{
class NestedWhileLoop
{
public static void Main(string[] args)
{
int i = 0;
do
{
int j = 0;
do
{
Console.Write("({0},{1}) ", i, j);
j++;
} while (j < 2);
i++;
Console.WriteLine();

} while (i < 2);


}
}
}

Output:

(0,0) (0,1)
(1,0) (1,1)

This program showcases the usage of nested do-while loops to print pairs of numbers.

Different Inner and Outer Nested Loops


It is not mandatory to nest loops of the same type. Different types of loops can be nested within each
other. For instance:

Example 5: Nested Loop with Different Inner and Outer Loops

using System;

namespace Loop
{
class NestedLoop
{
public static void Main(string[] args)
{
int i = 1;

Complete Note Of Csharp(C#): 57


while (i <= 5)
{
for (int j = 1; j <= i; j++)
{
Console.Write(i + " ");
}

Console.WriteLine();
i++;
}
}
}
}

Output:

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

In this program, a for loop is nested within a while loop, demonstrating the flexibility of nesting different
types of loops.

C# Break Statement
In C#, the break statement is utilized to terminate a loop prematurely. While loops iterate over a block of
code until the test expression is false, the break statement allows us to exit the loop immediately without
evaluating the test expression.

Example: C# break statement with for loop


using System;

namespace CSharpBreak
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 4; ++i)
{
// Terminates the loop when i is equal to 3
if (i == 3)
{
break;
}

Complete Note Of Csharp(C#): 58


Console.WriteLine(i);
}

Console.ReadLine();
}
}
}

Output:

1
2

In the above program, the for loop runs four times, but when i is equal to 3, the break statement is
encountered, causing the loop to terminate immediately. Consequently, only the values 1 and 2 are
printed.

Example: C# break statement with while loop


using System;

namespace WhileBreak
{
class Program
{
static void Main(string[] args)
{
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);

// Terminates the loop when i is equal to 4


if (i == 4)
{
break;
}

i++;
}

Console.ReadLine();
}
}
}

Output:

Complete Note Of Csharp(C#): 59


1
2
3

In this example, a while loop is used to run from i = 1 to i = 5 . However, the loop terminates when i is
equal to 4 due to the break statement.

Working of break statement in C#


The break statement terminates the loop immediately when encountered.

It is often used with decision-making statements like if..else .

Break Statement with Nested Loop


The break statement can also be used with nested loops. Consider the following example:

using System;

namespace NestedBreak
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
for (int i = 1; i <= 3; i++) // Outer loop
{
for (int j = 1; j <= 3; j++) // Inner loop
{
// Terminates the inner loop when i is equal to 2
if (i == 2)
{
break;
}

Console.WriteLine("i = " + i + " j = " + j);


}
}

Console.ReadLine();
}
}
}

Output:

i = 1 j = 1
i = 1 j = 2

Complete Note Of Csharp(C#): 60


i = 1 j = 3
i = 3 j = 1
i = 3 j = 2
i = 3 j = 3

In this example, the break statement is used inside the inner loop. Consequently, the inner loop terminates
when i is equal to 2, while the outer loop continues.

Break with foreach Loop


The break statement can also be applied to foreach loops:

using System;

namespace ForEachBreak
{
class Program
{
static void Main(string[] args)
{
int[] num = { 1, 2, 3, 4, 5 };

// Use of foreach loop


foreach (int number in num)
{
// Terminates the loop when number is equal to 3
if (number == 3)
{
break;
}

Console.WriteLine(number);
}
}
}
}

Output:

1
2

In this example, the foreach loop prints each element of the array, but it terminates when the element is
equal to 3 due to the break statement.

Break with switch Statement


The break statement is also applicable inside a switch case statement:

Complete Note Of Csharp(C#): 61


using System;

namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
char ch = 'e';

switch (ch)
{
case 'a':
Console.WriteLine("Vowel");
break;

case 'e':
Console.WriteLine("Vowel");
break;

case 'i':
Console.WriteLine("Vowel");
break;

case 'o':
Console.WriteLine("Vowel");
break;

case 'u':
Console.WriteLine("Vowel");
break;

default:
Console.WriteLine("Not a vowel");
break;
}
}
}
}

Output:

Vowel

Here, the break statement is used inside each case to terminate the switch statement when a matching
case is found.

Complete Note Of Csharp(C#): 62


C# continue Statement
In C#, the continue statement is employed to skip the current iteration of a loop. When encountered, the
program control moves to the end of the loop, reevaluates the test condition, and in the case of a for

loop, executes the update statement.

Example 1: C# continue with for loop


using System;

namespace ContinueLoop
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 5; ++i)
{
// Skips the iteration when i is equal to 3
if (i == 3)
{
continue;
}

Console.WriteLine(i);
}
}
}
}

Output:

1
2
4
5

In this example, the for loop is utilized to print numbers from i = 1 to 5 . However, the number 3 is not
printed because the continue statement is executed when i is equal to 3. This skips the current iteration
of the loop.

Example 2: C# continue with while loop

using System;

namespace ContinueWhile
{
class Program

Complete Note Of Csharp(C#): 63


{
static void Main(string[] args)
{
int i = 0;
while (i < 5)
{
i++;

// Skips the iteration when i is equal to 3


if (i == 3)
{
continue;
}

Console.WriteLine(i);
}
}
}
}

Output:

1
2
4
5

The continue statement is used inside the while loop in a similar manner. When the value of i is 3, the
continue statement is executed, skipping the print statement for that iteration.

Working of C# continue Statement


The continue statement skips the current iteration of both for and while loops.

It is often used with the if...else statement.

continue with Nested Loop


The continue statement is compatible with nested loops. For example:

using System;

namespace ContinueNested
{
class Program
{
static void Main(string[] args)
{
int sum = 0;

Complete Note Of Csharp(C#): 64


// Outer loop
for (int i = 1; i <= 3; i++)
{
// Inner loop
for (int j = 1; j <= 3; j++)
{
// Skips the iteration when j is equal to 2
if (j == 2)
{
continue;
}

Console.WriteLine("i = " + i + " j = " + j);


}
}
}
}
}

Output:

i = 1 j = 1
i = 1 j = 3
i = 2 j = 1
i = 2 j = 3
i = 3 j = 1
i = 3 j = 3

In this example, the continue statement is used inside the inner for loop. It skips the iteration when j is
equal to 2, resulting in the omission of the value 2 in the output.

C# continue with foreach Loop


The continue statement is also applicable to foreach loops:

using System;

namespace ContinueForeach
{
class Program
{
static void Main(string[] args)
{
int[] num = { 1, 2, 3, 4, 5 };

// Use of foreach loop


foreach (int number in num)
{
// Skips the iteration when number is equal to 3

Complete Note Of Csharp(C#): 65


if (number == 3)
{
continue;
}

Console.WriteLine(number);
}
}
}
}

Output:

1
2
4
5

Here, the foreach loop prints each element of the array, but it skips the value 3 when encountered, due to
the continue statement.

C# Arrays
An array in C# is a collection of elements of the same data type. Instead of creating separate variables, an
array allows you to store and manage multiple values more efficiently. Let's explore the essential concepts
related to arrays in C#.

1. C# Array Declaration
In C#, you declare an array using the following syntax:

dataType[] arrayName;

dataType : Represents the data type of the elements in the array (e.g., int , string , char ).

arrayName : Identifies the array.

For example:

int[] age;

To specify the number of elements an array can hold, you need to allocate memory using the new

keyword:

age = new int[5];

You can combine declaration and memory allocation in a single line:

int[] age = new int[5];

Complete Note Of Csharp(C#): 66


2. Array Initialization in C#
You can initialize an array during declaration:

int[] numbers = {1, 2, 3, 4, 5};

In this case, C# automatically determines the size of the array based on the number of elements provided.
You can also use index numbers to initialize elements individually:

int[] age = new int[5];

// Initializing array
age[0] = 12;
age[1] = 4;
age[2] = 5;
// ...

Note:

Array indices start at 0, and the last element's index is one less than the array size.

3. Accessing Array Elements


Accessing array elements involves using index numbers. For example:

// Access element at index 2


array[2];

// Access element at index 4


array[4];

You can use these indices to access specific elements in the array.

Example: C# Array
using System;

namespace AccessArray
{
class Program
{
static void Main(string[] args)
{
// Create an array
int[] numbers = {1, 2, 3};

// Access first element


Console.WriteLine("Element in the first index: " + numbers[0]);

Complete Note Of Csharp(C#): 67


// Access second element
Console.WriteLine("Element in the second index: " + numbers
[1]);

// Access third element


Console.WriteLine("Element in the third index: " + numbers[2]);

Console.ReadLine();
}
}
}

Output:

Element in the first index: 1


Element in the second index: 2
Element in the third index: 3

In this example, we use array indices to access elements of the array numbers .

4. Changing Array Elements


You can change array elements by assigning new values to specific indices. For instance:

// Create an array
int[] numbers = {1, 2, 3};

Console.WriteLine("Old Value at index 0: " + numbers[0]);

// Change the value at index 0


numbers[0] = 11;

// Print new value


Console.WriteLine("New Value at index 0: " + numbers[0]);

Output:

Old Value at index 0: 1


New Value at index 0: 11

Here, the value at index 0 is changed from 1 to 11.

5. Iterating C# Array using Loops


You can use loops to iterate through array elements. For example, using a for loop:

using System;

namespace AccessArrayFor

Complete Note Of Csharp(C#): 68


{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3};

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


{
Console.WriteLine("Element in index " + i + ": " + numbers
[i]);
}

Console.ReadLine();
}
}
}

Output:

Element in index 0: 1
Element in index 1: 2
Element in index 2: 3

Alternatively, you can use a foreach loop:

using System;

namespace AccessArrayForeach
{
class Program
{
static void Main(string[] args)
{
int[] numbers = {1, 2, 3};

Console.WriteLine("Array Elements: ");

foreach(int num in numbers)


{
Console.WriteLine(num);
}

Console.ReadLine();
}
}
}

Complete Note Of Csharp(C#): 69


Output:

Array Elements:
1
2
3

Here, numbers.Length provides the size of the array.

6. C# Array Operations using System.Linq


The System.Linq namespace offers various methods for array operations. For example, finding the
minimum and maximum elements:

using System;
using System.Linq;

namespace ArrayMinMax
{
class Program
{
static void Main(string[] args)
{
int[] numbers = {51, 1, 3, 4, 98};

// Get the minimum element


Console.WriteLine("Smallest Element: " + numbers.Min());

// Get the maximum element


Console.WriteLine("Largest Element: " + numbers.Max());

Console.ReadLine();
}
}
}

Output:

Smallest Element: 1
Largest Element: 98

Similarly, finding the average of an array:

using System;
using System.Linq;

namespace ArrayFunction
{
class Program

Complete Note Of Csharp(C#): 70


{
static void Main(string[] args)
{
int[] numbers = {30, 31, 94, 86, 55};

// Get the sum of all array elements


float sum = numbers.Sum();

// Get the total number of elements present in the array


int count = numbers.Count();

float average = sum / count;

Console.WriteLine("Average : " + average);

// Compute the average using Average()


Console.WriteLine("Average using Average() : " + numbers.Averag
e());

Console.ReadLine();
}
}
}

Output:

Average: 59.2
Average using Average(): 59.2

Remember to include the System.Linq namespace for methods like Min() , Max() , Sum() , Count() , and
Average() .

C# Multidimensional Array
Before delving into multidimensional arrays in C#, it's crucial to understand single-dimensional arrays. A
multidimensional array, in C#, comprises elements that are themselves arrays. For example:

int[,] x = { { 1, 2, 3 }, { 3, 4, 5 } };

Here, x is a multidimensional array with two elements: {1, 2, 3} and {3, 4, 5}. Each element of the array is
also an array with three elements.

1. Two-Dimensional Array Declaration


In C#, you declare a 2D array as follows:

int[,] x = new int[2, 3];

Complete Note Of Csharp(C#): 71


Here, x is a 2D array with 2 elements, and each element is also an array with 3 elements. The array,
therefore, can store a total of 6 elements (2 * 3).

2. Two-Dimensional Array Initialization


You can initialize a 2D array during declaration:

int[,] x = { { 1, 2, 3 }, { 3, 4, 5 } };

In this case, x is a 2D array with two elements: {1, 2, 3} and {3, 4, 5}. The number of rows and columns is
determined by the initialization.
You can also specify the number of rows and columns during initialization:

int[,] x = new int[2, 3] { { 1, 2, 3 }, { 3, 4, 5 } };

3. Accessing Elements from 2D Array


You use index numbers to access elements of a 2D array. For example:

// A 2D array
int[,] x = { { 1, 2, 3 }, { 3, 4, 5 } };

// Access the first element from the first row


x[0, 0]; // returns 1

// Access the third element from the second row


x[1, 2]; // returns 5

// Access the third element from the first row


x[0, 2]; // returns 3

Example: C# 2D Array
using System;

namespace MultiDArray
{
class Program
{
static void Main(string[] args)
{
// Initializing a 2D array
int[,] numbers = {{2, 3}, {4, 5}};

// Access the first element from the first row


Console.WriteLine("Element at index [0, 0] : " + numbers[0,
0]);

Complete Note Of Csharp(C#): 72


// Access the first element from the second row
Console.WriteLine("Element at index [1, 0] : " + numbers[1,
0]);
}
}
}

Output:

Element at index [0, 0] : 2


Element at index [1, 0] : 4

In this example, the program creates a 2D array named numbers with rows {2, 3} and {4, 5}. The index
numbers are used to access elements of the 2D array.

Changing Array Elements


You can change the elements of a two-dimensional array by assigning new values. For example:

using System;

namespace MultiDArray
{
class Program
{
static void Main(string[] args)
{
int[,] numbers = {{2, 3}, {4, 5}};

// Old element
Console.WriteLine("Old element at index [0, 0] : " + numbers[0,
0]);

// Assigning a new value


numbers[0, 0] = 222;

// New element
Console.WriteLine("New element at index [0, 0] : " + numbers[0,
0]);
}
}
}

Output:

Old element at index [0, 0] : 2


New element at index [0, 0] : 222

Complete Note Of Csharp(C#): 73


In this example, the initial value at index [0, 0] is 2. By assigning a new value of 222 at this index, the
value is changed accordingly.

Iterating C# Array using Loop


using System;

namespace MultiDArray
{
class Program
{
static void Main(string[] args)
{
int[,] numbers = { { 2, 3, 9 }, { 4, 5, 9 } };

for (int i = 0; i < numbers.GetLength(0); i++)


{
Console.Write("Row " + i + ": ");

for (int j = 0; j < numbers.GetLength(1); j++)


{
Console.Write(numbers[i, j] + " ");
}
Console.WriteLine();
}
}
}
}

Output:

Row 0: 2 3 9
Row 1: 4 5 9

This example uses a nested for loop to iterate through the elements of a 2D array. The GetLength(0)

method gives the number of rows, and GetLength(1) gives the number of elements in a row.
Note: You can also create a 3D array, which is essentially an array with multiple two-dimensional arrays as
its elements. For example:

int[,,] numbers = { { { 1, 3, 5 }, { 2, 4, 6 } }, { { 2, 4, 9 }, { 5, 7, 11
} } };

Here, [,,] denotes the 3D array.

C# Jagged Array

Complete Note Of Csharp(C#): 74


In C#, a jagged array is a structure consisting of multiple arrays as its elements. Unlike multidimensional
arrays, each array within a jagged array can have different sizes. Ensure familiarity with:

C# Arrays

C# Multidimensional Arrays

C# Jagged Array Declaration


Here's the syntax for declaring a jagged array in C#:

dataType[][] nameOfArray = new dataType[rows][];

For example:

// Declare jagged array


int[][] jaggedArray = new int[2][];

Here, int is the data type, [][] represents a jagged array, jaggedArray is the array's name, and [2][]

indicates the number of elements (arrays) inside the jagged array.


Since each element of a jagged array is also an array, individual array sizes can be set. For instance:

// Set size of the first array as 3


jaggedArray[0] = new int[3];

// Set size of the second array as 2


jaggedArray[1] = new int[2];

Initializing Jagged Array


Jagged arrays can be initialized in various ways. Examples include:

1. Using the index number

// Initialize the first array


jaggedArray[0][0] = 1;
jaggedArray[0][1] = 3;
jaggedArray[0][2] = 5;

// Initialize the second array


jaggedArray[1][0] = 2;
jaggedArray[1][1] = 4;

2. Initialize without setting the size of array elements

// Declaring a string jagged array


int[][] jaggedArray = new int[2][];

// Initialize each array

Complete Note Of Csharp(C#): 75


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

3. Initialize while declaring Jagged Array

int[][] jaggedArray = {
new int[] {10, 20, 30},
new int[] {11, 22},
new int[] {88, 99}
};

Accessing Elements of a Jagged Array


Elements of a jagged array can be accessed using index numbers. For example:

// Access the first element of the second array


jaggedArray[1][0];

// Access the second element of the second array


jaggedArray[1][1];

// Access the second element of the first array


jaggedArray[0][1];

Example: C# Jagged Array


using System;

namespace JaggedArray
{
class Program
{
static void Main(string[] args)
{
// Create a jagged array
int[][] jaggedArray = {
new int[] {1, 3, 5},
new int[] {2, 4},
};

// Print elements of jagged array


Console.WriteLine("jaggedArray[1][0]: " + jaggedArray[1][0]);
Console.WriteLine("jaggedArray[1][1]: " + jaggedArray[1][1]);
Console.WriteLine("jaggedArray[0][2]: " + jaggedArray[0][2]);

Console.ReadLine();

Complete Note Of Csharp(C#): 76


}
}
}

Output:

jaggedArray[1][0]: 2
jaggedArray[1][1]: 4
jaggedArray[0][2]: 5

In this example, within a jagged array:

jaggedArray[1][0] refers to the first element of the second array.

jaggedArray[1][1] refers to the second element of the second array.

jaggedArray[0][2] refers to the third element of the first array.

Iterating through a Jagged Array


In C#, loops can be utilized to iterate through each element of a jagged array. For example:

// Declare a jagged array


int[][] jaggedArray = new int[2][];

// Set size of Jagged Array Elements


jaggedArray[0] = new int[3];
jaggedArray[1] = new int[2];

// Initialize the first array


jaggedArray[0][0] = 1;
jaggedArray[0][1] = 3;
jaggedArray[0][2] = 5;

// Initialize the second array


jaggedArray[1][0] = 2;
jaggedArray[1][1] = 2;

// Outer for loop


for (int i = 0; i < jaggedArray.Length; i++)
{
Console.Write("Element " + i + ": ");

// Inner for loop


for (int j = 0; j < jaggedArray[i].Length; j++)
{
Console.Write(jaggedArray[i][j] + " ");
}
Console.WriteLine();
}

Complete Note Of Csharp(C#): 77


Console.ReadLine();

Output:

Element 0: 1 3 5
Element 1: 2 2

In this example, a nested for loop is used to iterate through the jagged array. The outer loop accesses
the elements (arrays) of the jagged array, and the inner loop accesses the elements of the individual
arrays inside the jagged array.

Jagged Array with Multidimensional Array


Jagged arrays in C# can also contain multidimensional arrays as elements. For instance:

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


new int[,] { {1, 8}, {6, 7} },
new int[,] { {0, 3}, {5, 6}, {9, 10} }
};

Here, each element of the jagged array is a multidimensional array. An example is provided:

using System;

namespace JaggedArray
{
class Program
{
static void Main(string[] args)
{
// Declare and initialize jagged array with 2D array
int[][,] jaggedArray = new int[3][,] {
new int[,] { {1, 8}, {6, 7} },
new int[,] { {0, 3}, {5, 6}, {9, 10} },
new int[,] { {11, 23}, {100, 88}, {0, 10} }
};

Console.WriteLine(jaggedArray[0][0, 1]);
Console.WriteLine(jaggedArray[1][2, 1]);
Console.WriteLine(jaggedArray[2][1, 0]);

Console.ReadLine();
}
}
}

Output:

Complete Note Of Csharp(C#): 78


8
10
100

In this example, the code jaggedArray[0][0, 1] refers to the second element of the first
array inside the 2D array.

C# foreach loop
C# provides a more readable and user-friendly alternative to the traditional for loop - the foreach loop. It
is particularly beneficial when working with arrays and collections, simplifying the iteration process. Before
delving into the details of the foreach loop, ensure familiarity with the following:

C# for loop

C# arrays

C# collections

Syntax of foreach loop


The syntax for the foreach loop in C# is as follows:

foreach (element in iterable-item)


{
// body of foreach loop
}

Here, iterable-item can be an array or a class of collection. The in keyword, used with the foreach loop,
iterates over the iterable-item . It selects an item from the iterable-item on each iteration and stores it in
the variable element .

How foreach loop works


The in keyword, in conjunction with the foreach loop, selects an item from the iterable-item on each
iteration and stores it in the variable element . The loop continues until all elements of the array or
collection are processed.

Example 1: Printing array using for loop

using System;

namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
char[] myArray = {'H','e','l','l','o'};

Complete Note Of Csharp(C#): 79


for(int i = 0; i < myArray.Length; i++)
{
Console.WriteLine(myArray[i]);
}
}
}
}

Example 2: Printing array using foreach loop

using System;

namespace Loop
{
class ForEachLoop
{
public static void Main(string[] args)
{
char[] myArray = {'H','e','l','l','o'};

foreach(char ch in myArray)
{
Console.WriteLine(ch);
}
}
}
}

In the above programs, both using for and foreach loops achieve the same task of printing each
character of the array. However, the foreach loop provides a more readable and concise syntax.

Example 3: Traversing an array of gender using foreach loop


This program computes the number of male and female candidates.

using System;

namespace Loop
{
class ForEachLoop
{
public static void Main(string[] args)
{
char[] gender = {'m','f','m','m','m','f','f','m','m','f'};
int male = 0, female = 0;
foreach (char g in gender)
{
if (g == 'm')

Complete Note Of Csharp(C#): 80


male++;
else if (g =='f')
female++;
}
Console.WriteLine("Number of male = {0}", male);
Console.WriteLine("Number of female = {0}", female);
}
}
}

Example 4: foreach loop with List (Collection)


This program computes the sum of elements in a List.

using System;
using System.Collections.Generic;

namespace Loop
{
class ForEachLoop
{
public static void Main(string[] args)
{
var numbers = new List<int>() { 5, -8, 3, 14, 9, 17, 0, 4 };
int sum = 0;
foreach (int number in numbers) {
sum += number;
}
Console.WriteLine("Sum = {0}", sum);
Console.ReadLine();
}
}
}

In this program, the foreach loop is used to traverse through a collection. Traversing a collection is similar
to traversing through an array, where each element of the collection is processed in order.
When using the foreach loop, the resulting code is often more readable and easier to understand
compared to the traditional for loop, especially when working with arrays and collections.

C# Class and Object


C# embraces the principles of object-oriented programming (OOP) to address complex problems by
breaking them down into manageable objects. Understanding classes is foundational in this paradigm, as
they serve as blueprints for creating objects.

C# Class

Complete Note Of Csharp(C#): 81


A class, analogous to a blueprint, defines the structure of an object. It encapsulates fields (variables) and
methods (functions) that the object will possess. The syntax for creating a class in C# is straightforward:

class ClassName {
// Fields
dataType fieldName;

// Methods
returnType MethodName() {
// Method body
}
}

For example:

class Dog {
// Field
string breed;

// Method
public void Bark() {
// Method body
}
}

In this illustration, Dog is the class with a field breed and a method Bark .

C# Objects
Objects are instances of classes. If a class is likened to a blueprint, objects are the actual houses built
from that blueprint. To create an object in C#, the new keyword is employed:

ClassName obj = new ClassName();

For instance, creating a Dog object:

Dog bullDog = new Dog();

Here, bullDog is an object of the Dog class.

Accessing Class Members using Object


Objects access class members (fields and methods) using the . (dot operator). For example:

bullDog.Breed = "Bull Dog";


Console.WriteLine(bullDog.Breed);
bullDog.Bark();

This demonstrates accessing the Breed field and invoking the Bark method of the Dog class.

Complete Note Of Csharp(C#): 82


Creating Multiple Objects of a Class
Multiple objects can be created from a single class. For instance:

Employee sheeran = new Employee();


sheeran.Department = "Development";

Employee taylor = new Employee();


taylor.Department = "Content Writing";

Both sheeran and taylor are objects of the Employee class, each with its own Department field.

Creating Objects in a Different Class


Objects can also be created in a different class. If class members are declared as public , they are
accessible from other classes:

Employee e1= new Employee();


e1.Name = "Gloria";
e1.Work("Coding");

This example involves creating an Employee object ( e1 ) in a different class ( EmployeeDrive ).

Why Objects and Classes?


Objects and classes facilitate the decomposition of a large project into manageable components. In a
hypothetical game project with numerous enemies, a single Enemy class can be created with shared fields
like health and ammo, and methods like Shoot() and Run() . Multiple enemy objects can then be
instantiated from this class, each maintaining its unique health and ammo values. OOP fosters code
reusability and aids in managing project complexity.

C# Method
A method in C# is a block of code designed to perform a specific task. In OOP, it aids in breaking down
complex problems into manageable units. Methods are crucial for creating modular and reusable code.

Declaring a Method in C#
The syntax for declaring a method in C# is as follows:

returnType MethodName() {
// method body
}

returnType: Specifies the type of value the method returns. If no value is returned, void is used.

MethodName: An identifier referring to the method.

method body: The block of code containing statements to perform specific tasks.

For example:

Complete Note Of Csharp(C#): 83


void Display() {
// code
}

Here, Display is the method name, and the return type is void .

Calling a Method in C#
After declaring a method, it needs to be called to execute the code within it. Calling a method is done
using the following syntax:

MethodName();

For example:

Display();

Example: C# Method
using System;

namespace Method {

class Program {

// method declaration
public void Display() {
Console.WriteLine("Hello World");
}

static void Main(string[] args) {

// create class object


Program p1 = new Program();

// call method
p1.Display();

Console.ReadLine();
}
}
}

Output:

Hello World

Complete Note Of Csharp(C#): 84


In this example, a method named Display is declared and called using an object of the class.

C# Method Return Type


A method in C# may or may not return a value. The return type is specified using the returnType keyword.
If a method returns no value, the return type is void . If it returns a value, the return statement is used.
Example:

using System;

namespace Method {

class Program {

// method declaration
static int AddNumbers() {
int sum = 5 + 14;
return sum;
}

static void Main(string[] args) {

// call method
int sum = AddNumbers();

Console.WriteLine(sum);

Console.ReadLine();
}
}
}

Output:

19

In this example, the method AddNumbers returns an int .

C# Methods Parameters
Methods in C# can accept parameters, allowing them to receive values during the call. Parameters are
specified within the method parentheses.

Example:

using System;

namespace Method {

Complete Note Of Csharp(C#): 85


class Program {
int AddNumber(int a, int b) {
int sum = a + b;
return sum;
}

static void Main(string[] args) {

// create class object


Program p1 = new Program();

// call method
int sum = p1.AddNumber(100, 100);

Console.WriteLine("Sum: " + sum);

Console.ReadLine();
}
}
}

Output:

Sum: 200

In this example, the method AddNumber takes two parameters.

Built-in Methods
C# provides built-in methods that can be used directly in programs. These include methods like Sqrt()

(square root) and ToUpper() (converts a string to uppercase).


Example:

using System;

namespace Method {

class Program {
static void Main(string[] args) {

// Built-in method
double a = Math.Sqrt(9);
Console.WriteLine("Square root of 9: " + a);
}
}
}

Output:

Complete Note Of Csharp(C#): 86


Square root of 9: 3

In this example, the Sqrt() method is used from the Math class.

Method Overloading in C#
C# supports method overloading, allowing the creation of multiple methods with the same name but
different parameters.
Example:

using System;

namespace MethodOverload {

class Program {

// method with one parameter


void Display(int a) {
Console.WriteLine("Arguments: " + a);
}

// method with two parameters


void Display(int a, int b) {
Console.WriteLine("Arguments: " + a + " and " + b);
}
static void Main(string[] args) {

Program p1 = new Program();


p1.Display(100);
p1.Display(100, 200);
Console.ReadLine();
}
}
}

Output:

Arguments: 100
Arguments: 100 and 200

In this example, the Display method is overloaded with different numbers of parameters.

C# Access Modifiers
Access modifiers in C# dictate the accessibility of types (e.g., classes, interfaces) and type members (e.g.,
fields, methods). They play a crucial role in controlling the visibility and interaction of different components
within a program.

Complete Note Of Csharp(C#): 87


Types of Access Modifiers
In C#, there are four basic types of access modifiers:

1. Public:

When a type or type member is declared as public, it can be accessed from anywhere.

Example:

class Student {
public string name = "Sheeran";

public void Print() {


Console.WriteLine("Hello from Student class");
}
}

In this example, both the name field and the Print method are public and can be accessed from the
Program class.

2. Private:

When a type member is declared as private, it can only be accessed within the same class or
struct.

Example:

class Student {
private string name = "Sheeran";

private void Print() {


Console.WriteLine("Hello from Student class");
}
}

In this case, attempting to access the name field or the Print method from the Program class would
result in an error.

3. Protected:

When a type member is declared as protected, it can only be accessed from the same class and
its derived classes.

Example:

class Student {
protected string name = "Sheeran";
}

class Program : Student {


static void Main(string[] args) {
// Error: 'Student.name' is inaccessible due to its protection level
Console.WriteLine("Name: " + name);

Complete Note Of Csharp(C#): 88


}
}

In this example, attempting to access the name field directly from the Program class results in an error.
However, it can be accessed within a derived class, as shown.

4. Internal:

When a type or type member is declared as internal, it can be accessed only within the same
assembly.

Example:

// Assembly1
class Student {
internal string name = "Sheeran";
}

// Assembly2
class Program {
static void Main(string[] args) {
// Accessing internal field from Assembly1
Console.WriteLine("Name: " + student.name);
}
}

In this example, the name field is internal, allowing access within the same assembly ( Assembly2 ).

5. Protected Internal:

The protected internal access modifier is a combination of protected and internal. It allows access
from the same assembly and the derived class of the containing class from any other assembly.

Example:

// Assembly1
public class Greet {
protected internal string msg = "Hello";
}

// Assembly2
class Program : Greet {
static void Main(string[] args) {
// Accessing protected internal field from Assembly1
Console.WriteLine(msg);
}
}

In this example, the msg field is protected internal, allowing access from the Program class in
Assembly2 .

6. Private Protected:

Complete Note Of Csharp(C#): 89


The private protected access modifier is a combination of private and protected. It is available
from C# version 7.2 and later. It allows access within the same class and its derived class within
the same assembly.

Example:

// Assembly1
public class StudentName {
private protected string name = "Sheeran";
}

// Assembly1, Derived Class


class Program1 : StudentName {
static void Main(string[] args) {
// Accessing private protected field from the same assembly
Console.WriteLine(name);
}
}

In this example, the name field is private protected, allowing access from the derived class Program1 in
the same assembly.

Conclusion
Access modifiers are essential for controlling the visibility and accessibility of types and members in C#.
Choosing the appropriate access modifier ensures that code is secure, encapsulated, and follows the
principles of encapsulation and information hiding. Understanding these modifiers is crucial for writing
maintainable and well-structured C# code.

C# Variable Scope
In C#, the scope of a variable refers to the regions of code where the variable is accessible and can be
used. C# has three main types of variable scope: Class Level Scope, Method Level Scope, and Block
Level Scope.

1. Class Level Variable Scope


Variables declared at the class level, known as fields, have class level scope. They can be accessed
throughout the entire class but are not accessible from static methods. For example:

using System;

namespace VariableScope {
class Program {

// Class level variable


string str = "Class Level";

public void Display() {

Complete Note Of Csharp(C#): 90


Console.WriteLine(str);
}

static void Main(string[] args) {


Program ps = new Program();
ps.Display();

Console.ReadLine();
}
}
}

In this example, the variable str is accessible within the class, including the Display method.

2. Method Level Variable Scope


Variables declared inside a method have method level scope. They are only accessible within the method
where they are declared and cannot be accessed from outside that method. For example:

using System;

namespace VariableScope {
class Program {

public void Method1() {


// Method level variable
string str = "Method Level";
}

public void Method2() {


// Attempting to access str from another method results in an error
Console.WriteLine(str); // Error
}

static void Main(string[] args) {


Program ps = new Program();
ps.Method2();

Console.ReadLine();
}
}
}

In this example, attempting to access the str variable from Method2 results in an error because str has
method level scope and is not accessible outside Method1 .

3. Block Level Variable Scope

Complete Note Of Csharp(C#): 91


Variables declared inside a block, such as a for loop or if statement, have block level scope. They are only
accessible within that block and cannot be accessed from outside. For example:

using System;

namespace VariableScope {
class Program {
public void Display() {

for (int i = 0; i <= 3; i++) {


// Block level variable
}
Console.WriteLine(i); // Error
}

static void Main(string[] args) {


Program ps = new Program();
ps.Display();

Console.ReadLine();
}
}
}

In this example, attempting to access the block level variable i outside the for loop results in an error
because i is only accessible within the block where it is declared.

C# Constructor
In C#, a constructor serves as a special method that is invoked when an object of a class is created. It
shares some similarities with methods, but there are key differences:

1. It has the same name as the class.

2. It does not have any return type.

Creating a C# Constructor
A constructor is defined within a class with the same name as the class itself. It is invoked automatically
when an object of the class is created. Here's an example:

class Car {
// Constructor
Car() {
// Code inside the constructor
}
}

In this example, Car() is a constructor with no parameters.

Complete Note Of Csharp(C#): 92


Calling a Constructor
Constructors are called using the new keyword when creating an object. For instance:

Car car1 = new Car();

This line of code creates an object car1 of the Car class, invoking its constructor.

Types of Constructors
1. Parameterless Constructor

When a constructor is created without parameters, it is known as a parameterless constructor.


Example:

class Car {
// Parameterless constructor
Car() {
Console.WriteLine("Car Constructor");
}
}

Here, new Car(); would invoke the parameterless constructor.

2. Parameterized Constructor
A constructor can also accept parameters, making it a parameterized constructor. Example:

class Car {
string brand;
int price;

// Parameterized constructor
Car(string theBrand, int thePrice) {
brand = theBrand;
price = thePrice;
}
}

Usage: Car car1 = new Car("Bugatti", 50000);

3. Default Constructor
If no constructor is defined, C# automatically creates a default constructor with an empty body.
Example:

class Program {
int a;

static void Main(string[] args) {


Program p1 = new Program();
Console.WriteLine("Default value of a: " + p1.a);

Complete Note Of Csharp(C#): 93


}
}

Here, Program p1 = new Program(); calls the default constructor.

4. Copy Constructor

A copy constructor is used to create an object by copying data from another object. Example:

class Car {
// Copy constructor
Car(Car c1) {
brand = c1.brand;
}
}

Usage: Car car2 = new Car(car1);

5. Private Constructor
A constructor can be made private, limiting object creation to within the class. Example:

class Car {
// Private constructor
private Car() {
Console.WriteLine("Private Constructor");
}
}

Usage: Car car1 = new Car(); would result in an error.

6. Static Constructor
A constructor can be static. It is called automatically, and there can be only one per class. Example:

class Car {
// Static constructor
static Car() {
Console.WriteLine("Static Constructor");
}
}

Usage: Car car1 = new Car();

Constructor Overloading
C# supports constructor overloading, where a class can have multiple constructors with different
parameter lists. Example:

class Car {
// Constructor with no parameter
Car() {

Complete Note Of Csharp(C#): 94


Console.WriteLine("Car constructor");
}

// Constructor with one parameter


Car(string brand) {
Console.WriteLine("Car constructor with one parameter");
Console.WriteLine("Brand: " + brand);
}
}

Usage:

Car car = new Car(); // Calls constructor with no parameter


Car car2 = new Car("Bugatti"); // Calls constructor with one parameter

By overloading constructors, a class can provide flexibility in object creation based on different scenarios.

C# this Keyword
In C#, the this keyword refers to the current instance of a class. It is primarily used to distinguish between
instance variables and parameters that share the same name. Here are some major uses of the this
keyword in C#:

1. Referencing Instance Variables


The this keyword is used to differentiate between instance variables and parameters with the same
name. Consider the following example:

using System;

namespace ThisKeyword {
class Test {

int num;

Test(int num) {
// this.num refers to the instance field
this.num = num;
Console.WriteLine("object of this: " + this);
}

static void Main(string[] args) {


Test t1 = new Test(4);
Console.WriteLine("object of t1: " + t1);
Console.ReadLine();
}
}
}

Complete Note Of Csharp(C#): 95


Here, this.num is used to refer to the instance variable num of the class, distinguishing it from the
constructor parameter num .

2. Handling Same Name Variables


In scenarios where instance variables and parameters share the same name, the this keyword helps
avoid confusion. For instance:

using System;

namespace ThisKeyword {
class Test {

int num;

Test(int num) {
// this.num refers to the instance field
this.num = num;
}

static void Main(string[] args) {


Test t1 = new Test(4);
Console.WriteLine("value of num: " + t1.num);
Console.ReadLine();
}
}
}

By using this.num , the code unambiguously refers to the instance variable, ensuring clarity in the program.

3. Constructor Chaining
The this keyword is used to invoke one constructor from another, a concept known as constructor
chaining. For example:

using System;

namespace ThisKeyword {
class Test {

Test(int num1, int num2) {


Console.WriteLine("Constructor with two parameters");
}

// invokes the constructor with 2 parameters


Test(int num) : this(33, 22) {
Console.WriteLine("Constructor with one parameter");
}

Complete Note Of Csharp(C#): 96


public static void Main(String[] args) {
Test t1 = new Test(11);
Console.ReadLine();
}
}
}

Here, this(33, 22) is used to call the constructor with two parameters from the constructor with one
parameter.

4. Passing Object as an Argument


The this keyword can be used to pass the current object as an argument to a method:

using System;

namespace ThisKeyword {
class Test {
int num1;
int num2;

Test() {
num1 = 22;
num2 = 33;
}

// method that accepts this as an argument


void passParameter(Test t1) {
Console.WriteLine("num1: " + num1);
Console.WriteLine("num2: " + num2);
}

void display() {
// passing this as a parameter
passParameter(this);
}

public static void Main(String[] args) {


Test t1 = new Test();
t1.display();
Console.ReadLine();
}
}
}

In this example, passParameter(this) passes the current object to the passParameter method, allowing
access to the object's attributes.

Complete Note Of Csharp(C#): 97


5. Declaring a C# Indexer
The this keyword is utilized to declare an indexer, enabling objects of a class to be indexed similar to
arrays:

using System;

namespace ThisKeyword {

class Student {
private string[] name = new string[3];

// declaring an indexer
public string this[int index] {
// returns the value of the array element
get {
return name[index];
}
// sets the value of the array element
set {
name[index] = value;
}
}
}

class Program {

public static void Main() {


Student s1 = new Student();
s1[0] = "Ram";
s1[1] = "Shyam";
s1[2] = "Gopal";

for (int i = 0; i < 3; i++) {


Console.WriteLine(s1[i] + " ");
}
}
}
}

Here, public string this[int index] defines an indexer, and the this keyword is used to reference the
object instance when accessing or setting values.

The this keyword plays a crucial role in maintaining clarity and avoiding ambiguity in code, especially in
scenarios involving similarly named variables and constructor chaining.

C# static Keyword

Complete Note Of Csharp(C#): 98


In C#, the static keyword is used with class members to create a single copy of the type member shared
by all objects of the class. This ensures that there is no need for individual copies for each object,
promoting memory efficiency. Below are some key uses of the static keyword in C#:

1. Static Variables
If a variable is declared static, it can be accessed using the class name. For instance:

using System;

namespace StaticKeyword {
class Student {
// static variable
public static string department = "Computer Science";
}

class Program {
static void Main(string[] args) {
// access static variable
Console.WriteLine("Department: " + Student.department);
Console.ReadLine();
}
}
}

In this example, the static variable department is accessed using the class name Student .

2. Static Variables Vs Instance Variables


In C#, every object of a class has its own copy of instance variables. However, if a variable is declared
static, all objects share the same static variable. This distinction is demonstrated below:

using System;

namespace StaticKeyword {
class Student {
static public string schoolName = "Programiz School";
public string studentName;
}

class Program {
static void Main(string[] args) {
Student s1 = new Student();
s1.studentName = "Ram";

// calls instance variable


Console.WriteLine("Name: " + s1.studentName);
// calls static variable
Console.WriteLine("School: " + Student.schoolName);

Complete Note Of Csharp(C#): 99


Student s2 = new Student();
s2.studentName = "Shyam";

// calls instance variable


Console.WriteLine("Name: " + s2.studentName);
// calls static variable
Console.WriteLine("School: " + Student.schoolName);

Console.ReadLine();
}
}
}

In this program, schoolName is a static variable shared by all students, demonstrating efficiency.

3. Static Methods
Static methods can be called using the class name, and all objects of the class share the same static
method. For instance:

class Test {
public static void display() {....}
}

class Program {
static void Main(string[] args) {
Test.display();
}
}

Here, the static method display is accessed directly from the Program class using the class name.

4. Static and Non-static Methods


Both static and non-static methods can coexist in a class. Non-static methods are called using object
instances, while static methods are called using the class name. Example:

using System;

namespace StaticKeyword {
class Test {
public void display1() {
Console.WriteLine("Non-static method");
}
public static void display2() {
Console.WriteLine("Static method");
}
}

Complete Note Of Csharp(C#): 100


class Program {
static void Main(string[] args) {
Test t1 = new Test();
t1.display1();
Test.display2();
Console.ReadLine();
}
}
}

In this example, display1 is a non-static method called using an object instance ( t1 ), while display2 is a
static method called using the class name.

5. Static Class
When a class is declared as static, no objects of the class can be created. All members within a static
class must also be static. Example:

using System;

namespace StaticKeyword {
static class Test {
static int a = 5;
static void display() {
Console.WriteLine("Static method");
}

static void Main(string[] args) {


// creating object of Test
Test t1 = new Test();
Console.WriteLine(a);
display();
}
}
}

Attempting to create an object of a static class results in an error, promoting the idea that static classes
cannot be instantiated.

6. Accessing Static Members within the Class


If accessing static variables and methods within the same class, they can be directly accessed without
using the class name. For instance:

using System;

namespace StaticKeyword {
class Test {

Complete Note Of Csharp(C#): 101


static int age = 25;
public static void display() {
Console.WriteLine("Static method");
}

static void Main(string[] args) {


Console.WriteLine(age);
display();
Console.ReadLine();
}
}
}

Here, static field age and static method display are accessed directly without using the class name.

The static keyword plays a crucial role in promoting memory efficiency and creating shared resources
across objects. Its usage ensures a single copy of type members shared by all instances, leading to
optimized program execution.

C# String
In C#, a string is a sequence of characters, represented by the string keyword. Strings are immutable,
meaning that once created, their values cannot be changed. The string class in C# provides various
methods to perform operations on strings.

Example: Creating a String in C#


using System;

namespace CsharpString {
class Test {
public static void Main(string[] args) {
// create string
string str1 = "C# Programming";
string str2 = "Programiz";

// print strings
Console.WriteLine(str1);
Console.WriteLine(str2);

Console.ReadLine();
}
}
}

In this example, two strings ( str1 and str2 ) are created and printed.

String Operations

Complete Note Of Csharp(C#): 102


1. Get the Length of a String

using System;

namespace CsharpString {
class Test {
public static void Main(string[] args) {
// create string
string str = "C# Programming";
Console.WriteLine("string: " + str);

// get length of str


int length = str.Length;
Console.WriteLine("Length: " + length);

Console.ReadLine();
}
}
}

The Length property is used to find the total number of characters in the string.

2. Join Two Strings in C#

using System;

namespace CsharpString {
class Test {
public static void Main(string[] args) {
// create strings
string str1 = "C# ";
Console.WriteLine("string str1: " + str1);

string str2 = "Programming";


Console.WriteLine("string str2: " + str2);

// join two strings


string joinedString = string.Concat(str1, str2);
Console.WriteLine("Joined string: " + joinedString);

Console.ReadLine();
}
}
}

Strings can be joined using the Concat() method or the + operator.

3. Compare Two Strings in C#

Complete Note Of Csharp(C#): 103


using System;

namespace CsharpString {
class Test {
public static void Main(string[] args) {
// create strings
string str1 = "C# Programming";
string str2 = "C# Programming";
string str3 = "Programiz";

// compare str1 and str2


bool result1 = str1.Equals(str2);
Console.WriteLine("string str1 and str2 are equal: " + result1);

// compare str1 and str3


bool result2 = str1.Equals(str3);
Console.WriteLine("string str1 and str3 are equal: " + result2);

Console.ReadLine();
}
}
}

The Equals() method is used to check if two strings are equal.

Immutability of String Objects


Strings in C# are immutable. Any operation that seems to modify a string creates a new string object. For
example:

string str = "Hello ";


str = string.Concat(str, "World");

Here, a new string is created by adding "World" to the original string "Hello ". The original string is then
released for garbage collection.

String Escape Sequences


Escape characters are used to insert special characters inside a string. For example:

string str = "This is the \\"String\\" class.";

Here, the escape sequence \\" is used to include a double quote inside the string.

String Interpolation
String interpolation allows inserting variables inside a string using the $ character:

using System;

Complete Note Of Csharp(C#): 104


namespace CsharpString {
class Test {
public static void Main(string[] args) {
// create string
string name = "Programiz";

// string interpolation
string message = $"Welcome to {name}";
Console.WriteLine(message);

Console.ReadLine();
}
}
}

Here, the variable name is inserted into the string using {} braces within a string literal starting with $ .

Methods of C# string
Some commonly used string methods in C# are:

Format() : Returns a formatted string.

Split() : Splits the string into substrings.

Substring() : Returns a substring of a string.

Compare() : Compares string objects.

Replace() : Replaces specified characters.

Contains() : Checks if the string contains a substring.

Join() : Joins strings using a specified separator.

Trim() : Removes leading and trailing whitespaces.

EndsWith() : Checks if the string ends with a given string.

IndexOf() : Returns the position of a specified character.

Remove() : Returns characters from a string.

ToUpper() : Converts the string to uppercase.

ToLower() : Converts the string to lowercase.

PadLeft() , PadRight() : Pads the string with spaces or specified characters.

StartsWith() : Checks if the string begins with a given string.

ToCharArray() : Converts the string to a char array.

LastIndexOf() : Returns the index of the last occurrence of a specified string.

C# Inheritance
In C#, inheritance is a fundamental concept of Object-Oriented Programming (OOP) that enables the
creation of a new class (derived class) based on an existing class (base class). This promotes code reuse

Complete Note Of Csharp(C#): 105


and establishes an "is-a" relationship between classes.

Performing Inheritance in C#
In C#, the : symbol is used to denote inheritance. Here's a simple example:

class Animal {
// fields and methods
}

// Dog inherits from Animal


class Dog : Animal {
// additional fields and methods specific to Dog
}

In this example, the Dog class is derived from the Animal class, inheriting its fields and methods.

Example: C# Inheritance
using System;

namespace Inheritance {

// base class
class Animal {
public string name;

public void display() {


Console.WriteLine("I am an animal");
}
}

// derived class of Animal


class Dog : Animal {

public void getName() {


Console.WriteLine("My name is " + name);
}
}

class Program {

static void Main(string[] args) {


// object of derived class
Dog labrador = new Dog();

// access field and method of base class


labrador.name = "Rohu";

Complete Note Of Csharp(C#): 106


labrador.display();

// access method from own class


labrador.getName();

Console.ReadLine();
}

}
}

In this example, a subclass Dog is derived from the superclass Animal . The Dog class inherits the name

field and display() method from Animal . An object of the Dog class is then used to access both the
inherited and its own methods.

Types of Inheritance
1. Single Inheritance:
In single inheritance, a single derived class inherits from a single base class.

2. Multilevel Inheritance:
In multilevel inheritance, a derived class inherits from a base class, and then another class inherits
from this derived class.

3. Hierarchical Inheritance:
In hierarchical inheritance, multiple derived classes inherit from a single base class.

4. Multiple Inheritance:
Multiple inheritance is not supported in C#, but it can be achieved through interfaces.

5. Hybrid Inheritance:
Hybrid inheritance is a combination of two or more types of inheritance.

Protected Members in C# Inheritance


Members declared as protected can be accessed within the same class and its derived classes. For
example:

using System;

namespace Inheritance {

// base class
class Animal {
protected void eat() {
Console.WriteLine("I can eat");
}
}

// derived class of Animal


class Dog : Animal {

Complete Note Of Csharp(C#): 107


static void Main(string[] args) {

Dog labrador = new Dog();

// access protected method from base class


labrador.eat();

Console.ReadLine();
}
}
}

In this example, the eat() method is declared as protected in the Animal class, and it can be accessed
from the Dog class.

Method Overriding in C# Inheritance


Method overriding allows a derived class to provide a specific implementation for a method already
defined in the base class. The virtual keyword in the base class and override keyword in the derived
class are used for this purpose. Example:

using System;

namespace Inheritance {

// base class
class Animal {
public virtual void eat() {
Console.WriteLine("I eat food");
}
}

// derived class of Animal


class Dog : Animal {

// overriding method from Animal


public override void eat() {
Console.WriteLine("I eat Dog food");
}
}
class Program {

static void Main(string[] args) {


// object of derived class
Dog labrador = new Dog();

// accesses overridden method


labrador.eat();
}

Complete Note Of Csharp(C#): 108


}
}

In this example, the eat() method in the Dog class overrides the same method in the Animal class.

Using the base Keyword in C# Inheritance


The base keyword is used to call the method of the base class from the derived class. Example:

using System;

namespace Inheritance {

// base class
class Animal {
public virtual void eat() {
Console.WriteLine("Animals eat food.");
}
}

// derived class of Animal


class Dog : Animal {

// overriding method from Animal


public override void eat() {
// call method from Animal class
base.eat();
Console.WriteLine("Dogs eat Dog food.");
}
}
class Program {

static void Main(string[] args) {


Dog labrador = new Dog();
labrador.eat();
}
}
}

In this example, the eat() method in the Dog class uses the base keyword to access the method of the
Animal class.

Importance of Inheritance in C#
Inheritance is crucial for promoting code reusability and establishing relationships between classes.
Consider an example where a RegularPolygon class has a method to calculate the perimeter, and Square

and Rectangle classes inherit from it:

Complete Note Of Csharp(C#): 109


using System;

namespace Inheritance {

class RegularPolygon {

public void calculatePerimeter(int length, int sides) {


int result = length * sides;
Console.WriteLine("Perimeter: " + result);
}
}

class Square : RegularPolygon {

public int length = 200;


public int sides = 4;
public void calculateArea() {
int area = length * length;
Console.WriteLine("Area of Square: " + area);
}
}

class Rectangle : RegularPolygon {

public int length = 100;


public int breadth = 200;
public int sides = 4;

public void calculateArea() {


int area = length * breadth;
Console.WriteLine("Area of Rectangle: " + area);
}
}

class Program {

static void Main(string[] args) {

Square s1 = new Square();


s1.calculateArea();
s1.calculatePerimeter(s1.length, s1.sides);

Rectangle t1 = new Rectangle();


t1.calculateArea();
t1.calculatePerimeter(t1.length, t1.sides);
}

Complete Note Of Csharp(C#): 110


}
}

In this example, the Square and Rectangle classes reuse the calculatePerimeter() method from the base
class RegularPolygon . This demonstrates how inheritance enhances code organization and reuse.

C# Abstract Class and Method


In C#, an abstract class is a class that cannot be instantiated directly. The abstract keyword is used to
define an abstract class. It may contain both abstract methods (methods without a body) and non-abstract
methods (methods with a body). Objects cannot be created from an abstract class; instead, it serves as a
base class for derived classes.

Abstract Class Example


// create an abstract class
abstract class Language {
// fields and methods
}

In the above example, Language is an abstract class with no specific implementation.

Inheriting from an Abstract Class


Since objects cannot be created from an abstract class, a derived class must be created to access its
members. Here's an example:

using System;

namespace AbstractClass {

abstract class Language {


// non-abstract method
public void display() {
Console.WriteLine("Non-abstract method");
}
}

// inheriting from the abstract class


class Program : Language {
static void Main (string [] args) {
// object of Program class
Program obj = new Program();

// access method of the abstract class


obj.display();

Console.ReadLine();

Complete Note Of Csharp(C#): 111


}
}
}

In this example, Program is a class derived from the abstract class Language . The display() method of the
abstract class is accessed using an object of the Program class.

Abstract Method
An abstract method is a method without a body, marked with the abstract keyword. It must be present
inside an abstract class. A non-abstract class inheriting from an abstract class should provide an
implementation for all the abstract methods.

Example: Implementation of Abstract Method

using System;

namespace AbstractClass {

abstract class Animal {


// abstract method
public abstract void makeSound();
}

// inheriting from abstract class


class Dog : Animal {
// provide implementation of abstract method
public override void makeSound() {
Console.WriteLine("Bark Bark");
}
}

class Program {
static void Main (string [] args) {
// create an object of Dog class
Dog obj = new Dog();
obj.makeSound();

Console.ReadLine();
}
}
}

In this example, the Animal abstract class has an abstract method makeSound() . The derived class Dog

provides an implementation for this abstract method.

Abstract Class with Get and Set Accessors


Get and set accessors can also be marked as abstract. Here's an example:

Complete Note Of Csharp(C#): 112


using System;

namespace AbstractClass {
abstract class Animal {
protected string name;
// abstract method
public abstract string Name { get; set; }
}

// inheriting from abstract class


class Dog : Animal {
// provide implementation of abstract method
public override string Name {
get { return name; }
set { name = value; }
}
}

class Program {
static void Main (string [] args) {
// create an object of Dog class
Dog obj = new Dog();
obj.Name = "Tom";
Console.WriteLine("Name: " + obj.Name);

Console.ReadLine();
}
}
}

In this example, the Name property of the Animal abstract class has abstract get and set accessors. The
derived class Dog provides an implementation for these accessors.

Access Constructor of Abstract Classes


Abstract classes can have constructors, and they are called when an object of a derived class is created.
For example:

using System;

namespace AbstractClass {
abstract class Animal {
public Animal() {
Console.WriteLine("Animal Constructor");
}
}

class Dog : Animal {

Complete Note Of Csharp(C#): 113


public Dog() {
Console.WriteLine("Dog Constructor");
}
}

class Program {
static void Main (string [] args) {
// create an object of Dog class
Dog d1 = new Dog();

Console.ReadLine();
}
}
}

In this example, both the Animal abstract class and the derived class Dog have constructors. When an
object of the Dog class is created, the constructor of the abstract class Animal is also called.

C# Abstraction
Abstraction is a key concept in object-oriented programming, and abstract classes are used to achieve it in
C#. Abstraction involves hiding unnecessary details and exposing only what is needed. It simplifies
complex systems by presenting a higher-level idea.

Example: C# Abstraction

using System;

namespace AbstractClass {
abstract class MotorBike {
public abstract void brake();
}

class SportsBike : MotorBike {


// provide implementation of abstract method
public override void brake() {
Console.WriteLine("Sports Bike Brake");
}
}

class MountainBike : MotorBike {


// provide implementation of abstract method
public override void brake() {
Console.WriteLine("Mountain Bike Brake");
}
}

class Program {

Complete Note Of Csharp(C#): 114


static void Main (string [] args) {
// create an object of SportsBike class
SportsBike s1 = new SportsBike();
s1.brake();

// create an object of MountainBike class


MountainBike m1 = new MountainBike();
m1.brake();

Console.ReadLine();
}
}
}

In this example, the abstract class MotorBike has an abstract method brake() . The derived classes
SportsBike and MountainBike provide their own implementations of the brake() method. This demonstrates

how abstraction allows different implementations while maintaining a common interface.

C# Nested Class
In C#, a nested class is a class defined within another class. The nested class is also referred to as an
inner class. It encapsulates and organizes the code more effectively, providing a way to logically structure
classes within the scope of another class.

Example of Nested Class


using System;

namespace CsharpNestedClass {

// outer class
public class Car {

public void displayCar() {


Console.WriteLine("Car: Bugatti");
}

// inner class
public class Engine {
public void displayEngine() {
Console.WriteLine("Engine: Petrol Engine");
}
}
}

class Program {
static void Main(string[] args) {

Complete Note Of Csharp(C#): 115


// create object of outer class
Car sportsCar = new Car();

// access method of outer class


sportsCar.displayCar();

// create object of inner class


Car.Engine petrolEngine = new Car.Engine();

// access member of inner class


petrolEngine.displayEngine();

Console.ReadLine();
}
}
}

In the above program, the Engine class is nested inside the Car class. Objects of both the outer class
( Car ) and the inner class ( Engine ) are created to access their respective methods.

Accessing Members of Nested Class


To access members of the nested classes, objects need to be created for each class:

1. Create an object of the outer class:

Car sportsCar = new Car();

2. Create an object of the inner class:

Car.Engine petrolEngine = new Car.Engine();

Now, these objects can be used to access the methods of their respective classes.

Accessing Outer Class Members Inside Inner Class


Inside the inner class, members of the outer class can be accessed by creating an object of the outer
class:

using System;

namespace CsharpNestedClass {

// outer class
public class Car {
public string brand = "Bugatti";

// nested class

Complete Note Of Csharp(C#): 116


public class Engine {
public void displayCar() {

// object of outer class


Car sportsCar = new Car();
Console.WriteLine("Brand: " + sportsCar.brand);
}
}
}

class Program {
static void Main(string[] args) {

// object of inner class


Car.Engine engineObj = new Car.Engine();
engineObj.displayCar();

Console.ReadLine();
}
}
}

In this example, the Engine class accesses the brand field of the outer class Car by creating an object of
Car .

Accessing Static Members of Outer Class Inside Inner Class


If static members of the outer class need to be accessed inside the inner class, there is no need to create
an object. Instead, the name of the outer class can be directly used:

using System;

namespace CsharpNestedClass {

// outer class
public class Car {
//static member of outer class
public static string brand = "Bugatti";

// nested class
public class Engine {
public void display() {

// access static member of outer class


Console.WriteLine("Brand: " + Car.brand);
}
}
}
class Program {

Complete Note Of Csharp(C#): 117


static void Main(string[] args) {

// object of inner class


Car.Engine obj = new Car.Engine();
obj.display();

Console.ReadLine();
}
}
}

In this example, the static field brand of the outer class Car is accessed directly inside the inner class
Engine .

Inheriting Outer and Inner Classes


Inheriting Outer Class:

Like regular classes, the outer class can be inherited:

using System;

namespace CsharpNestedClass {

// outer class
class Computer {

public void display() {


Console.WriteLine("Method of Computer class");
}
}

// derived class
class Laptop : Computer {

class Program {
static void Main(string[] args) {

// object of derived class


Laptop obj = new Laptop();
obj.display();

Console.ReadLine();
}
}
}

Complete Note Of Csharp(C#): 118


In this example, the Laptop class is derived from the Computer class, allowing access to the display()

method of the outer class.

Inheriting Inner Class:


Inner classes can also be inherited:

using System;

namespace CsharpNestedClass {

// outer class
class Computer {

// nested class
public class CPU {
public void display() {
Console.WriteLine("Method of CPU class");
}
}
}

// inheriting inner class


class Laptop : Computer.CPU {

class Program {
static void Main(string[] args) {

// object of derived class


Laptop obj = new Laptop();
obj.display();

Console.ReadLine();
}
}
}

In this example, the Laptop class is derived from the inner class CPU of the outer class Computer . The
inheritance syntax uses the name of the outer class along with the nested class.

C# Partial Class and Partial Method


Introduction to Partial Class
In C#, a partial class allows splitting the definition of a class across multiple source files. This feature
proves beneficial in scenarios involving large-scale projects with multiple developers working on the

Complete Note Of Csharp(C#): 119


same class simultaneously. The use of the partial keyword is essential for splitting a class definition,
and all parts are combined during compilation.

Example 1:
Consider a project named HeightWeightInfo that represents height and weight information. In this
project, two files ( File1.cs and File2.cs ) contribute to a partial class named Record .

File1.cs

namespace HeightWeightInfo
{
class File1
{
}

public partial class Record


{
private int h;
private int w;

public Record(int h, int w)


{
this.h = h;
this.w = w;
}
}
}

File2.cs

namespace HeightWeightInfo
{
class File2
{
}

public partial class Record


{
public void PrintRecord()
{
Console.WriteLine("Height:" + h);
Console.WriteLine("Weight:" + w);
}
}
}

Program.cs

Complete Note Of Csharp(C#): 120


namespace HeightWeightInfo
{
class Program
{
static void Main(string[] args)
{
Record myRecord = new Record(10, 15);
myRecord.PrintRecord();
Console.ReadLine();
}
}
}

In this example, File1.cs and File2.cs contribute to the same Record class. The Record class is
instantiated in the Main method of Program.cs .

Key Points:

The partial keyword allows combining class attributes defined in various files into a single class.

Useful for collaborative development on large projects.

All parts of the class should be in the same namespace and have the same access modifier.

Introduction to Partial Methods


A partial class may include a partial method. One part of the class contains the method's signature,
and an optional implementation may exist in the same part or another part. If no implementation is
provided, the method and its calls are removed during compilation.

Example 2:
Consider a partial class Car defined in File1.cs with a partial method InitializeCar() . Another part of
the class in File2.cs contains the implementation of InitializeCar() .

File1.cs

public partial class Car


{
partial void InitializeCar();
public void BuildRim() { }
public void BuildWheels() { }
}

File2.cs

public partial class Car


{
public void BuildEngine() { }
partial void InitializeCar()
{

Complete Note Of Csharp(C#): 121


string str = "Car";
}
}

Key Points:

A partial method declaration consists of two parts: the definition and the implementation.

They may be in separate parts or the same part of the partial class.

Partial methods are implicitly private, have a return type of void, and cannot be virtual.

C# Sealed Class and Method


Sealed Class
In C#, a sealed class is employed when we want to prevent the class from being inherited by another
class. The sealed keyword is used to declare a sealed class. Consider the following example:

using System;

namespace SealedClass {
sealed class Animal {

// Trying to inherit from a sealed class


// Error Code
class Dog : Animal {

class Program {
static void Main (string [] args) {

// Creating an object of the Dog class


Dog d1 = new Dog();
Console.ReadLine();
}
}
}

In the example, a sealed class Animal is defined. An attempt to derive the Dog class from the sealed
class results in an error, as a sealed class cannot have a derived class.

Key Points:

Sealed classes prevent inheritance, ensuring that no other class can derive from them.

The sealed keyword is used to declare a class as sealed.

Complete Note Of Csharp(C#): 122


Sealed Method
During method overriding, if there's a requirement to prevent an overridden method from being further
overridden by another class, the method can be declared as a sealed method. The sealed keyword is
used with an overridden method to create a sealed method. Observe the following example:

using System;

namespace SealedClass {

class Animal {
public virtual void makeSound() {
Console.WriteLine("Animal Sound");
}
}

class Dog : Animal {

// Sealed method
sealed public override void makeSound() {
Console.WriteLine("Dog Sound");
}
}

class Puppy : Dog {

// Trying to override sealed method


public override void makeSound() {
Console.WriteLine("Puppy Sound");
}
}

class Program {
static void Main (string [] args) {

// Creating an object of the Puppy class


Puppy d1 = new Puppy();
Console.ReadLine();
}
}
}

In the example, the makeSound() method is overridden inside the Dog class, and the method is sealed
using the sealed keyword. Attempting to further override this method in the Puppy class results in an
error.
Key Points:

Sealed methods are used to prevent further overriding in multilevel inheritance.

Complete Note Of Csharp(C#): 123


Sealing methods ensures that the overridden method cannot be manipulated by subsequent
derived classes.

Why Sealed Class?


1. Preventing Inheritance:

Sealed classes are employed to avoid inheritance. This prevents manipulation of the methods
in the sealed class by other classes.

Example:

sealed class A {
// ...
}

// Error code - Cannot inherit from a sealed class


class B : A {
// ...
}

2. Security Measures:

By sealing classes, security issues can be mitigated. Sealed classes ensure that methods
cannot be overridden, enhancing security.

3. Static Members:

Sealed classes are particularly useful when dealing with classes containing static members.
For instance, the Pens class in the System.Drawing namespace is a sealed class that has static
members representing pens with standard colors. Sealing such classes ensures that their
static members are not modified or manipulated.

Example:

sealed class Pens {


// ...
}

C# Interface
In C#, an interface resembles an abstract class, but with a distinct feature: all methods within an
interface are fully abstract, meaning they lack a body. The interface keyword is employed to
create an interface. For instance:

interface IPolygon {

// Method without a body


void calculateArea();
}

Complete Note Of Csharp(C#): 124


Here:

IPolygon is the name of the interface.

By convention, interface names start with 'I' to easily identify them.

Access modifiers cannot be used within an interface.

All members of an interface are public by default.

Interfaces do not allow fields.

Implementing an Interface
Objects cannot be created from an interface; instead, other classes must implement it. Similar to
C# inheritance, the : symbol is used for interface implementation. Consider the example below:

using System;

namespace CsharpInterface {

interface IPolygon {
// Method without a body
void calculateArea(int l, int b);
}

class Rectangle : IPolygon {

// Implementation of methods inside the interface


public void calculateArea(int l, int b) {
int area = l * b;
Console.WriteLine("Area of Rectangle: " + area);
}
}

class Program {
static void Main (string [] args) {

Rectangle r1 = new Rectangle();

r1.calculateArea(100, 200);
}
}
}

In this example, the IPolygon interface is created with a method calculateArea(int l, int b) without
implementation. The Rectangle class then implements this interface, providing an implementation
for the calculateArea method.

Implementing Multiple Interfaces


In contrast to inheritance, a class can implement multiple interfaces. Example:

Complete Note Of Csharp(C#): 125


using System;

namespace CsharpInterface {

interface IPolygon {
// Method without a body
void calculateArea(int a, int b);
}

interface IColor {
void getColor();
}

// Implements two interfaces


class Rectangle : IPolygon, IColor {

// Implementation of IPolygon interface


public void calculateArea(int a, int b) {
int area = a * b;
Console.WriteLine("Area of Rectangle: " + area);
}

// Implementation of IColor interface


public void getColor() {
Console.WriteLine("Red Rectangle");
}
}

class Program {
static void Main (string [] args) {

Rectangle r1 = new Rectangle();

r1.calculateArea(100, 200);
r1.getColor();
}
}
}

In this example, two interfaces, IPolygon and IColor , are created. The Rectangle class implements
both interfaces. Consequently, the Rectangle class must provide implementations for the methods
of both interfaces.

Using Reference Variable of an Interface


A reference variable of an interface can be used. Example:

Complete Note Of Csharp(C#): 126


using System;

namespace CsharpInterface {

interface IPolygon {
// Method without a body
void calculateArea(int l, int b);
}

class Rectangle : IPolygon {

// Implementation of methods inside the interface


public void calculateArea(int l, int b) {
int area = l * b;
Console.WriteLine("Area of Rectangle: " + area);
}
}

class Program {
static void Main (string [] args) {

// Using a reference variable of the interface


IPolygon r1 = new Rectangle();

r1.calculateArea(100, 200);
}
}
}

In this example, an interface named IPolygon is created with a method calculateArea(int l, int b)

without implementation. A reference variable of the interface IPolygon is then used, pointing to the
Rectangle class that implements it.

Practical Example of Interface


Consider a practical example of C# Interface:

using System;

namespace CsharpInterface {

interface IPolygon {
// Method without a body
void calculateArea();
}

// Implements the interface


class Rectangle : IPolygon {

Complete Note Of Csharp(C#): 127


// Implementation of IPolygon interface
public void calculateArea() {
int l = 30;
int b = 90;
int area = l * b;
Console.WriteLine("Area of Rectangle: " + area);
}
}

class Square : IPolygon {

// Implementation of IPolygon interface


public void calculateArea() {
int l = 30;
int area = l * l;
Console.WriteLine("Area of Square: " + area);
}
}

class Program {
static void Main (string [] args) {

Rectangle r1 = new Rectangle();


r1.calculateArea();

Square s1 = new Square();


s1.calculateArea();
}
}
}

In this program, an interface IPolygon is created with an abstract method calculateArea() . Two
classes, Square and Rectangle , implement the IPolygon interface. Each class provides an
independent implementation of the calculateArea() method. The program then demonstrates
creating objects of both classes and invoking their respective calculateArea() methods.

Advantages of C# Interface
Interfaces offer several advantages in C#:

1. Achieving Abstraction:

Similar to abstract classes, interfaces help achieve abstraction by hiding the


implementation details of methods.

2. Specifications:

Interfaces provide specifications that a class must adhere to. For example, the IPolygon

interface specifies that any class implementing it must provide an implementation for the
calculateArea method.

Complete Note Of Csharp(C#): 128


3. Multiple Inheritance:

Unlike classes, which cannot inherit from multiple classes, a class can implement multiple
interfaces.

4. Loose Coupling:

Interfaces promote loose coupling, meaning that changes in one part of the code have
minimal or no impact on other parts of the code. In the provided example, modifying the
implementation of calculateArea() in the Square class does not affect the Rectangle class.

In summary, interfaces contribute to code organization, maintainability, and flexibility by enforcing


standards and promoting abstraction.

C# Method Overloading
In C#, method overloading allows having two or more methods in a class with the same name but
different numbers, types, or order of parameters. This provides flexibility and improves code
readability. The return types of overloaded methods may differ, but they must have distinct
parameters.

1. Changing the Number of Parameters


Example:

using System;

namespace MethodOverload {

class Program {

// Method with one parameter


void display(int a) {
Console.WriteLine("Arguments: " + a);
}

// Method with two parameters


void display(int a, int b) {
Console.WriteLine("Arguments: " + a + " and " + b);
}

static void Main(string[] args) {


Program p1 = new Program();
p1.display(100);
p1.display(100, 200);
Console.ReadLine();
}
}
}

Complete Note Of Csharp(C#): 129


Output:

Arguments: 100
Arguments: 100 and 200

In this example, the display() method is overloaded with different numbers of parameters. Based
on the number of arguments passed during the method call, the corresponding method is invoked.

2. Changing the Data Types of Parameters


Example:

using System;

namespace MethodOverload {

class Program {

// Method with int parameter


void display(int a) {
Console.WriteLine("int type: " + a);
}

// Method with string parameter


void display(string b) {
Console.WriteLine("string type: " + b);
}

static void Main(string[] args) {


Program p1 = new Program();
p1.display(100);
p1.display("Programiz");
Console.ReadLine();
}
}
}

Output:

int type: 100


string type: Programiz

In this example, the display() method is overloaded with different data types of parameters.
Depending on the type of arguments passed during the method call, the corresponding method is
executed.

3. Changing the Order of Parameters

Complete Note Of Csharp(C#): 130


Example:

using System;

namespace MethodOverload {

class Program {

// Method with int and string parameters


void display(int a, string b) {
Console.WriteLine("int: " + a);
Console.WriteLine("string: " + b);
}

// Method with string and int parameters


void display(string b, int a) {
Console.WriteLine("string: " + b);
Console.WriteLine("int: " + a);
}

static void Main(string[] args) {


Program p1 = new Program();
p1.display(100, "Programming");
p1.display("Programiz", 400);
Console.ReadLine();
}
}
}

Output:

int: 100
string: Programming
string: Programiz
int: 400

In this example, the display() method is overloaded by changing the order of parameters. The
method called depends on the order of arguments passed during the method call.

Method overloading provides a powerful mechanism for creating more readable and flexible code
by accommodating variations in method signatures based on different use cases.

C# Constructor Overloading
In C#, constructor overloading allows defining two or more constructors within the same class,
sharing the same name but differing in the number, types, or order of parameters. This provides
flexibility in creating instances of a class with varied initialization options.

Complete Note Of Csharp(C#): 131


1. Different Number of Parameters
Example:

using System;

namespace ConstructorOverload {

class Car {

// Constructor with no parameter


Car() {
Console.WriteLine("Car constructor");
}

// Constructor with one parameter


Car(string brand) {
Console.WriteLine("Car constructor with one parameter");
Console.WriteLine("Brand: " + brand);
}

static void Main(string[] args) {

// Call with no parameter


Car car = new Car();

Console.WriteLine();

// Call with one parameter


Car car2 = new Car("Bugatti");

Console.ReadLine();
}
}
}

Output:

Car constructor

Car constructor with one parameter


Brand: Bugatti

In this example, the Car class has two constructors, one with no parameters and another with a
single string parameter. Depending on the arguments passed during the constructor call, the
corresponding constructor is invoked.

2. Different Types of Parameters

Complete Note Of Csharp(C#): 132


Example:

using System;

namespace ConstructorOverload {

class Car {

// Constructor with string parameter


Car(string brand) {
Console.WriteLine("Brand: " + brand);
}

// Constructor with int parameter


Car(int price) {
Console.WriteLine("Price: " + price);
}

static void Main(string[] args) {

// Call constructor with string parameter


Car car = new Car("Lamborghini");

Console.WriteLine();

// Call constructor with int parameter


Car car2 =new Car(50000);

Console.ReadLine();
}
}
}

Output:

Brand: Lamborghini

Price: 50000

In this example, the Car class is overloaded with constructors having different types of
parameters. The appropriate constructor is called based on the type of arguments passed during
the constructor invocation.

3. Different Order of Parameters


Example:

Complete Note Of Csharp(C#): 133


using System;

namespace ConstructorOverload {

class Car {

// Constructor with string and int parameters


Car(string brand, int price) {
Console.WriteLine("Brand: " + brand);
Console.WriteLine("Price: " + price);
}

// Constructor with int and string parameters


Car(int speed, string color) {
Console.WriteLine("Speed: " + speed + " km/hr");
Console.WriteLine("Color: " + color);
}

static void Main(string[] args) {

// Call constructor with string and int parameters


Car car = new Car("Bugatti", 50000);

Console.WriteLine();

// Call constructor with int and string parameters


Car car2 =new Car(60, "Red");

Console.ReadLine();
}
}
}

Output:

Brand: Bugatti
Price: 50000

Speed: 60 km/hr
Color: Red

In this example, the Car class showcases constructor overloading with a different order of
parameters. The constructor called depends on the order of arguments passed during the
constructor invocation.

Constructor overloading in C# enhances the flexibility and usability of classes by allowing varied
ways to initialize objects based on the specific needs of the application.

Complete Note Of Csharp(C#): 134


C# using Directive
In C#, the using keyword is employed to import external resources such as namespaces, classes,
etc., into a program. This facilitates the usage of classes from the specified namespaces directly in
the code. Here's an example:

// using System namespace


using System;

namespace Program {

class Program1 {
static void Main(string[] args) {
Console.WriteLine("Hello World!");
}
}
}

Output:

Hello World!

In the above example, the line using System; imports the System namespace into the program,
allowing direct use of classes like Console . Without the using directive, the fully qualified name of
the Console class would be required:

// full print statement


System.Console.WriteLine("Hello World!");

// print statement with using System;


Console.WriteLine("Hello World!");

C# using to Create an Alias


Aliases can be created using the using directive in C#. This is particularly useful when dealing
with class names that might cause conflicts. For example:

// creating alias for System.Console


using Programiz = System.Console;

namespace HelloWorld {

class Program {
static void Main(string[] args) {

// using Programiz alias instead of System.Console


Programiz.WriteLine("Hello World!");
}

Complete Note Of Csharp(C#): 135


}
}

Output:

Hello World!

In this example, an alias Programiz is created for System.Console , allowing the use of Programiz

instead of System.Console .

C# using static Directive


The using static directive in C# enables the import of classes into a program so that their static
members (fields, methods) can be used directly. Here's an example using System.Math :

using System;

// using static directive


using static System.Math;

namespace Program {

class Program1 {
public static void Main(string[] args) {

double n = Sqrt(9);
Console.WriteLine("Square root of 9 is " + n);
}
}
}

Output:

Square root of 9 is 3

In this example, the line using static System.Math; allows direct access to the Sqrt() method from
the Math class. Without the using static directive, the fully qualified name would be required:

double n = Math.Sqrt(9);

The using static directive enhances code readability and conciseness by eliminating the need for
class qualification.

C# Type Conversion
Type conversion in C# involves the process of converting the value of one type (e.g., int, float,
double) to another type. There are two main types of type conversion in C#:

Complete Note Of Csharp(C#): 136


1. Implicit Type Conversion:
In implicit type conversion, the C# compiler automatically converts one type to another. This
typically happens when smaller types are converted to larger types, ensuring no loss of data
during conversion.
Example: Implicit Type Conversion

using System;

namespace MyApplication {
class Program {
static void Main(string[] args) {
int numInt = 500;
Type n = numInt.GetType();

// Implicit Conversion
double numDouble = numInt;
Type n1 = numDouble.GetType();

// Value before conversion


Console.WriteLine("numInt value: " + numInt);
Console.WriteLine("numInt Type: " + n);

// Value after conversion


Console.WriteLine("numDouble value: " + numDouble);
Console.WriteLine("numDouble Type: " + n1);
Console.ReadLine();
}
}
}

Output:

numInt value: 500


numInt Type: System.Int32
numDouble value: 500
numDouble Type: System.Double

2. Explicit Type Conversion (Type Casting):


In explicit type conversion, developers explicitly convert one type to another. This is often
required when converting larger types to smaller types, and it may result in data loss.

Example: Explicit Type Conversion

using System;

namespace MyApplication {
class Program {
static void Main(string[] args) {

Complete Note Of Csharp(C#): 137


double numDouble = 1.23;

// Explicit casting
int numInt = (int)numDouble;

// Value before conversion


Console.WriteLine("Original double Value: " + numDouble);

// Value before conversion


Console.WriteLine("Converted int Value: " + numInt);
Console.ReadLine();
}
}
}

Output:

Original double value: 1.23


Converted int value: 1

3. Type Conversion using Parse():


The
Parse()method is used for type conversion between non-compatible types, such as
converting a string to an int.

Example: Type Conversion using Parse()

using System;

namespace Conversion {
class Program {
static void Main(string[] args) {
string n = "100";

// converting string to int type


int a = int.Parse(n);
Console.WriteLine("Original string value: " + n);
Console.WriteLine("Converted int value: " + a);
Console.ReadLine();
}
}
}

Output:

Original string value: 100


Converted int value: 100

Complete Note Of Csharp(C#): 138


4. Type Conversion using Convert Class:
The
Convert class provides various methods for type conversion between different types.

Example: Convert int to String and Double

using System;

namespace Conversion {
class Program {
static void Main(string[] args) {
// create int variable
int num = 100;
Console.WriteLine("int value: " + num);

// convert int to string


string str = Convert.ToString(num);
Console.WriteLine("string value: " + str);

// convert int to Double


Double doubleNum = Convert.ToDouble(num);
Console.WriteLine("Double value: " + doubleNum);

Console.ReadLine();
}
}
}

Output:

int value: 100


string value: 100
Double value: 100

Example: Convert string to Double and vice-versa

using System;

namespace Conversion {
class Program {
static void Main(string[] args) {
// create string variable
string str = "99.99";
Console.WriteLine("Original string value: " + str);

// convert string to double


Double newDouble = Convert.ToDouble(str);
Console.WriteLine("Converted Double value: " + newDouble);

Complete Note Of Csharp(C#): 139


// create double variable
double num = 88.9;
Console.WriteLine("Original double value: " + num);

// converting double to string


string newString = Convert.ToString(num);
Console.WriteLine("Converted string value: " + newString);

Console.ReadLine();
}
}
}

Output:

Original string value: 99.99


Converted Double value: 99.99
Original double value: 88.9
Converted string value: 88.9

Example 3: Convert int to Boolean

using System;

namespace Conversion {
class Program {
static void Main(string[] args) {
// create int variables
int num1 = 0;
int num2 = 1;

// convert int to Boolean


Boolean bool1 = Convert.ToBoolean(num1);
Boolean bool2 = Convert.ToBoolean(num2);

Console.WriteLine("Boolean value of 0 is: " + bool1);


Console.WriteLine("Boolean value of 1 is: " + bool2);

Console.ReadLine();
}
}
}

Output:

Boolean value of 0 is: False


Boolean value of 1 is: True

Complete Note Of Csharp(C#): 140


In summary, C# provides various mechanisms for type conversion, both implicit and explicit, as
well as through methods like Parse() and the Convert class. Developers can choose the
appropriate method based on their specific requirements, considering factors such as data loss
and compatibility between types.

C# Preprocessor Directives
Preprocessor directives in C# are commands for the compiler that influence the compilation
process. They are processed before actual compilation begins, and they control which sections of
code are compiled or how specific errors and warnings are handled. These directives start with a
# (hash) symbol and last for one line, terminated by a new line.

Available Preprocessor Directives


1. #if Directive
Checks if a preprocessor expression is true or not.
Syntax:

#if preprocessor-expression
code to compile
#endif

2. #elif Directive
Used along with #if to check multiple preprocessor expressions.
Syntax:

#if preprocessor-expression-1
code to compile
#elif preprocessor-expression-2
code to compile
#endif

3. #else Directive
Used along with #if to create a compound conditional directive.
Syntax:

#if preprocessor-expression
code to compile
#elif
code to compile
#endif

4. #endif Directive
Indicates the end of a conditional directive.

Complete Note Of Csharp(C#): 141


Syntax:

#if preprocessor-expression
code to compile
#endif

5. #define Directive
Used to define a symbol.
Syntax:

#define SYMBOL

6. #undef Directive
Used to undefine a symbol.

Syntax:

#undef SYMBOL

7. #warning Directive
Generates a level 1 warning from the code.

Syntax:

#warning warning-message

8. #error Directive
Generates an error from the code.

Syntax:

#error error-message

9. #line Directive
Modifies the compiler's line number and filename for displaying errors and warnings.

Syntax:

#line line-number file-name

10. #region Directive


Creates a region that can be expanded or collapsed in a Visual Studio Code Editor.

Syntax:

Complete Note Of Csharp(C#): 142


#region region-description
codes
#endregion

11. #endregion Directive


Indicates the end of a region.

Syntax:

#region region-description
codes
#endregion

12. #pragma Directive


Gives the compiler special instructions for the compilation of the file.

Syntax:

#pragma pragma-name pragma-arguments

Example: Conditional Compilation


#define CSHARP

using System;

namespace Directive
{
class ConditionalDirective
{
public static void Main(string[] args)
{
#if (CSHARP)
Console.WriteLine("CSHARP is defined");
#endif
}
}
}

In this example, the #define directive defines the symbol CSHARP . Inside the Main method, the #if

directive checks if CSHARP is true. If true, the code block inside the #if is compiled.

Example: Multiple Conditions with #elif


#define TESTING

Complete Note Of Csharp(C#): 143


using System;

namespace Directive
{
class ConditionalDirective
{
static void Main(string[] args)
{
#if (TESTING)
Console.WriteLine("Currently Testing");
#elif (TRAINING)
Console.WriteLine("Currently Training");
#else
Console.WriteLine("Neither Testing nor Training");
#endif
}
}
}

In this example, the #elif directive is used along with #if to check multiple preprocessor
expressions. The code block inside the first true condition is compiled.

Example: User-Defined Warning and Error


using System;

namespace Directive
{
class WarningError
{
public static void Main(string[] args)
{
#warning This is a warning message
#error This is an error message
}
}
}

In this example, the #warning directive generates a warning, and the #error directive generates an
error. The program terminates if an error is encountered.

Example: #region and #endregion


using System;

namespace Directive
{
class RegionExample

Complete Note Of Csharp(C#): 144


{
public static void Main(string[] args)
{
#region Hello
Console.WriteLine("Hello");
Console.WriteLine("Hello");
Console.WriteLine("Hello");
Console.WriteLine("Hello");
Console.WriteLine("Hello");
#endregion
}
}
}

In this example, the #region and #endregion directives create a region in the code that can be
expanded or collapsed when using a Visual Studio Code Editor.

Example: #pragma to Disable and Enable Warnings


using System;

namespace Directive
{
class PragmaExample
{
public static void Main(string[] args)
{
#pragma warning disable
#warning This is a warning 1
#pragma warning restore
#warning This is a warning 2
}
}
}

In this example, the #pragma warning disable directive disables warnings, and #pragma warning
restore enables warnings. Only the second warning is displayed on the output screen.

These examples demonstrate the usage of various C# preprocessor directives for conditional
compilation, organization, and special instructions for the compiler. Each directive serves a
specific purpose and enhances the flexibility and control over the compilation process.

Namespaces in C# Programming
In C#, namespaces are employed to organize and provide a level of separation for code
components. They serve as containers that can include other namespaces, classes, interfaces,
structures, and delegates. Namespaces play a crucial role in writing cleaner code and managing
larger projects.

Complete Note Of Csharp(C#): 145


Consider a real-life analogy where numerous files and folders exist on a computer. Managing
them would be challenging if they were all placed in a single directory. Similarly, namespaces in
C# assist in organizing different members by grouping related ones together. They also address
the issue of naming conflicts, allowing two or more classes to share the same name when placed
in different namespaces.

Defining Namespace in C#
Namespaces are defined using the namespace keyword, with the syntax:

namespace NamespaceName
{
// Body of the namespace
}

For example:

namespace MyNamespace
{
class MyClass
{
public void MyMethod()
{
System.Console.WriteLine("Creating my namespace");
}
}
}

In this example, the MyNamespace namespace is created, containing a class MyClass with a method
MyMethod .

Accessing Members of Namespace in C#


Members of a namespace are accessed using the dot ( . ) operator, with the syntax:

NamespaceName.MemberName

For instance, to create an object of MyClass , you can use:

MyNamespace.MyClass myClass = new MyNamespace.MyClass();

Example 1: Introducing Namespace in C# Program


using System;

namespace MyNamespace
{
public class SampleClass

Complete Note Of Csharp(C#): 146


{
public static void MyMethod()
{
Console.WriteLine("Creating my namespace");
}
}
}

namespace MyProgram
{
public class MyClass
{
public static void Main()
{
MyNamespace.SampleClass.MyMethod();
}
}
}

When executed, this program outputs:

Creating my namespace

In this example, a namespace MyNamespace is created, and its members are accessed from the
Main method within MyClass . The dot ( . ) operator is used to access the namespace's members.

Using a Namespace in C# [The using Keyword]


A namespace can be included in a program using the using keyword. This eliminates the need to
specify the fully qualified name of the namespace's members every time they are accessed.

For instance:

using System;

After including this line, you can use Console.WriteLine("Hello World!"); instead of the fully qualified
name System.Console.WriteLine("Hello World!"); .

Nested Namespace in C#
A namespace can contain another namespace, forming a nested namespace. The nested
namespace and its members are accessed using the dot ( . ) operator.

The syntax for creating a nested namespace is:

namespace MyNamespace
{
namespace NestedNamespace
{
// Body of nested namespace

Complete Note Of Csharp(C#): 147


}
}

Example 2: Nested Namespace in C#


using System;

namespace MyNamespace
{
namespace Nested
{
public class SampleClass
{
public static void MyMethod()
{
Console.WriteLine("Nested Namespace Example");
}
}
}
}

namespace MyProgram
{
public class MyClass
{
public static void Main()
{
MyNamespace.Nested.SampleClass.MyMethod();
}
}
}

When executed, this program outputs:

Nested Namespace Example

This example demonstrates the implementation of a nested namespace in C#. A namespace


named Nested is created inside MyNamespace . The members are accessed using the dot ( . )
operator.

C# Struct
In C#, a struct (structure) is similar to a class and is used to store data. However, unlike classes,
a struct is a value type.

Suppose we want to store the name and age of a person. We can create two variables, name and
age , to store values. However, if we want to store the same information for multiple people,

Complete Note Of Csharp(C#): 148


creating variables for each individual might be cumbersome. To overcome this, we can create a
struct that stores the name and age, and this struct can be used for every person.

Define struct in C#
In C#, the struct keyword is used to define a struct. For example:

struct Employee
{
public int id;
}

Here, id is a field inside the struct. A struct can include methods, indexers, etc.

Declare struct variable


Before using a struct, a struct variable needs to be created. We use the struct name with a
variable to declare a struct variable. For example:

struct Employee
{
public int id;
}

// declare emp of struct Employee


Employee emp;

In this example, a struct named Employee is created, and a variable emp of the struct Employee is
declared.

Access C# struct
A struct variable is accessed using the dot ( . ) operator to access its members. For example:

struct Employee
{
public int id;
}

// declare emp of struct Employee


Employee emp;

// access member of struct


emp.id = 1;

Here, the variable emp of struct Employee is used with the dot ( . ) operator to access the id field
of the struct.

Note: Primitive data types like int , bool , and float are pre-defined structs in C#.

Complete Note Of Csharp(C#): 149


Example: C# Struct
using System;

namespace CsharpStruct
{
// defining struct
struct Employee
{
public int id;

public void GetId(int id)


{
Console.WriteLine("Employee Id: " + id);
}
}

class Program
{
static void Main(string[] args)
{
// declare emp of struct Employee
Employee emp;

// accesses and sets struct field


emp.id = 1;

// accesses struct methods


emp.GetId(emp.id);

Console.ReadLine();
}
}
}

Output:

Employee Id: 1

In this program, a struct named Employee is created, which contains a field id and a method
GetId() . A variable emp of struct Employee is declared and used to access fields and methods of

the struct.

Note: We can also instantiate a struct using the new keyword. For example:

Employee emp = new Employee();

Here, this line calls the parameterless constructor of the struct and initializes all the members with
default values.

Complete Note Of Csharp(C#): 150


Constructors in C# struct
In C#, a struct can include constructors. For example:

struct Employee
{
public int id;

// constructor
public Employee(int employeeId)
{
id = employeeId;
}
}

Here, a parameterized constructor Employee() with a parameter employeeId is created.

Note: C# version 9.0 or below does not allow creating parameterless constructors in a struct.

Example: Constructor in C# structs


using System;

namespace CsharpStruct
{
// defining struct
struct Employee
{
public int id;

public string name;

// parameterized constructor
public Employee(int employeeId, string employeeName)
{
id = employeeId;
name = employeeName;
}
}

class Program
{
static void Main(string[] args)
{
// calls constructor of struct
Employee emp = new Employee(1, "Brian");

Console.WriteLine("Employee Name: " + emp.name);


Console.WriteLine("Employee Id: " + emp.id);

Complete Note Of Csharp(C#): 151


Console.ReadLine();
}
}
}

Output:

Employee Name: Brian


Employee Id: 1

In this example, a parameterized constructor is created inside the Employee struct. The constructor
assigns values to fields id and name . The constructor is called using the new keyword.
Note: Values for every field of a struct must be assigned inside the parameterized constructor. For
example:

// error code
public Employee(int employeeID, employeeName)
{
id = employeeID;
}

Here, the value for the name field is not assigned, and the code will generate an error.

Properties in C# struct
Properties can also be used inside a C# struct. For example:

using System;

namespace CsharpStruct
{
// defining struct
struct Employee
{
public int id;

// creates property
public int Id
{
// returns id field
get
{
return id;
}

// sets id field
set

Complete Note Of Csharp(C#): 152


{
id = value;
}
}
}

class Program
{
static void Main(string[] args)
{
// calls the constructor of struct
Employee emp = new Employee();

emp.Id = 1;
Console.WriteLine("Employee Id: " + emp.Id);

Console.ReadLine();
}
}
}

Output:

Employee Id: 1

In this example, the Id property is created inside the Employee struct. The get method returns the
id field, and the set method assigns the value to the id field.

Difference between class and struct in C#


In C#, classes and structs look similar, but there are differences between them.

A class is a reference type, whereas a struct is a value type. For example:

using System;

namespace CsharpStruct
{
// defining class
class Employee
{
public string name;
}

class Program
{
static void Main(string[] args)
{
Employee emp1 = new Employee();

Complete Note Of Csharp(C#): 153


emp1.name = "John";

// assign emp1 to emp2


Employee emp2 = emp1;
emp2.name = "Ed";
Console.WriteLine("Employee1 name: " + emp1.name);

Console.ReadLine();
}
}
}

Output:

Employee1 name: Ed

In this example, the value of emp1 is assigned to emp2 . The emp2 object refers to the same object
as emp1 . Therefore, an update in emp2 updates the value of emp1 automatically. This is why a
class is a reference type.
Contrary to classes, when we assign one struct variable to another, the value of the struct gets
copied to the assigned variable. So, updating one struct variable doesn't affect the other. For
example:

using System;

namespace CsharpStruct
{
//

defining struct
struct Employee
{
public string name;
}

class Program
{
static void Main(string[] args)
{
Employee emp1 = new Employee();
emp1.name = "John";

// assign emp1 to emp2


Employee emp2 = emp1;
emp2.name = "Ed";
Console.WriteLine("Employee1 name: " + emp1.name);

Console.ReadLine();

Complete Note Of Csharp(C#): 154


}
}
}

Output:

Employee1 name: John

When we assign the value of emp1 to emp2 , a new value emp2 is created. The value of emp1 is
copied to emp2 , so a change in emp2 does not affect emp1 . This is why a struct is a value type.

Moreover, inheritance is not possible in structs, whereas it is an important feature of C# classes.

Complete Note Of Csharp(C#): 155

You might also like