C#
(C-Sharp)
C# (C-Sharp)
• C# is pronounced "C-Sharp".
• It is an object-oriented programming
language created by Microsoft that runs
on the .NET Framework.
• C# has roots from the C family, and the
language is close to other popular
languages like C++ and Java.
• The first version was released in year
2002. The latest version, C# 13, was
released in 2021.
C# Uses
• C# is used for:
• Mobile applications
• Desktop applications
• Web applications
• Web services
• Web sites
• Games
• VR
• Database applications
• And much, much more!
Reason to use C#
• It is easy to learn and simple to use
• It has a huge community support
• C# is an object oriented language which
gives a clear structure to programs and
allows code to be reused, lowering
development costs
• As C# is close to C, C++ and Java, it
makes it easy for programmers to switch
to C# or vice versa
C# Syntax
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Save : Program.cs
Output:
C# Syntax Explanation
(1)
• using System means that we can use classes from
the System namespace.
• A blank line. C# ignores white space. However,
multiple lines makes the code more readable.
• namespace is used to organize your code, and it is
a container for classes and other namespaces.
• The curly braces {} marks the beginning and the
end of a block of code.
• Class is a container for data and methods, which
brings functionality to your program. Every line of
code that runs in C# must be inside a class. In our
example, we named the class Program.
C# Syntax Explanation
(2)
• Console is a class of the System namespace,
which has a WriteLine() method that is used to
output/print text. In our example it will output
"Hello World!".
• If you omit the using System line, you would
have to write System.Console.WriteLine() to
print/output text.
Note:
✔Every C# statement ends with a semicolon ;.
✔C# is case-sensitive: "MyClass" and "myclass"
has different meaning.
C# Output
• Method1 :
Console.WriteLine("Hello World!");
• Method2 :
string name = "John";
Console.WriteLine(name);
• Method3 :
Console.WriteLine(3+3);
C# Comments
• Comments can be used to explain C# code, and to make it more
readable. It is of 2 types,
1. Single-line Comments
2. Multi-line Comments
• Single-line Comments
Single-line comments start with two forward slashes (//).Any
text between // and the end of the line is ignored by C# (will not be
executed).
Sample Program:
// This is a comment
Console.WriteLine("Hello World!");
(Or)
Console.WriteLine("Hello World!"); // This is a comment
C# Comments
Multi-line Comments
• Multi-line comments start with /* and
ends with */.
• Any text between /* and */ will be ignored
by C#.
Sample Program:
/*The code below will print the words Hello
World to the screen, and it is amazing */
Console.WriteLine("Hello World!");
C# Data Types
Data Type Size Description
int 4 bytes Stores whole numbers from -2,147,483,648 to
2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7
decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal
digits
bool 1 bit Stores true or false values
char 2 bytes Stores a single character/letter, surrounded by single
quotes
string 2 Stores a sequence of characters, surrounded by double
bytes quotes
/char
DT Examples
int num = 100000;
long lNum = 15000000000L;
float fNum = 5.75F;
double dNum = 19.99D;
//Scientific Numbers - "e" to indicate the power of 10
float f1 = 35e3F;
double d1 = 12E4D;
bool isCSharpFun = true;
char myGrade = 'B';
string greeting = "Hello World";
DT Examples Output
Ouput:
100000
15000000000
5.75
19.99
35000
120000
True
B
Hello World
C# Variables
• In C#, there are different types of variables
(defined with different keywords), for example:
✔ int - stores integers (whole numbers), without
decimals, such as 123 or -123
✔ double - stores floating point numbers, with
decimals, such as 19.99 or -19.99
✔ char - stores single characters, such as 'a' or 'B'.
Char values are surrounded by single quotes
✔ string - stores text, such as "Hello World".
String values are surrounded by double quotes
✔ bool - stores values with two states: true or
false
Variables Declaration
• Syntax:
dtype variableName =
value;
• Output:
• Example: John
string name = "John";
int myNum; 15
myNum = 15; D
char myLetter = 'D'; A
myLetter = 'A'; // myLetter is
now A
C# Constants
• The variable declared as "constant", which
means unchangeable and read-only. you can add
the const keyword in front of the variable type.
• Example:
const int myNum = 15;
myNum = 20;
O/p:
The left-hand side of an assignment must be a
variable, a property or an indexer.
C# Identifiers
• All C# variables must
be identified with unique names.
• These unique names are called identifiers.
• Identifiers can be short names (like x and y)
or more descriptive names (age, sum,
totalVolume).
• Examples:
int minutesPerHour = 60; // Good
int m = 60; // OK, but not so easy to
understand what m actually is ?
C# Input
(1)
Console.ReadLine() to get user input.
Example 1:
Console.WriteLine("Enter username:");
string userName = Console.ReadLine();
Console.WriteLine("Username is: " +
userName);
Output:
Enter username: Priya
Username is: Priya
C# Input
(2)
Other than string,
Example 2:
Console.WriteLine("Enter your age:");
int age = Console.ReadLine(); // error
Console.WriteLine("Your age is: " + age);
Output:
Cannot implicitly convert type 'string' to 'int‘
Replace : int age = Console.ReadLine();
With:
int age = Convert.ToInt32(Console.ReadLine());
C# Operators
• Operators are used to perform operations
on variables and values.
• Types:
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
Arithmetic Operators
Operators are used to perform operations
on variables and values.
Operator Name Description Example
+ Addition Adds together two values x+y
- Subtraction Subtracts one value from x-y
another
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division x%y
remainder
++ Increment Increases the value of a x++
variable by 1
-- Decrement Decreases the value of a x--
variable by 1
Comparison Operators
• Comparison operators are used to compare
two values (or variables).
• This is important in programming, because it
helps us to find answers and make decisions.
• The return value of a comparison is either
True or False.
• Example,
int a = 10;
int b = 5;
Console.WriteLine(a > b);
// returns True because 10 is greater than 5
All Comparison Operators
Operator Name Example
== Equal to a == b
!= Not equal a != b
> Greater than a>b
< Less than a<b
>= Greater than or a >= b
equal to
<= Less than or a <= b
equal to
Logical Operators
• Logical operators are used to determine
the logic between variables or values.
• We can also test for True or False values
with logical operators.
Operator Name Description Example
&& Logical and Returns True if both x < 5 && x < 10
statements are true
|| Logical or Returns True if one of the x < 5 || x < 4
statements is true
! Logical not Reverse the result, !(x < 5 && x < 10)
returns False if the result
is true
Assignment Operators
• Assignment operators are used to assign
values to variables.
• we use the assignment operator (=) to
assign the value.
• Example: int a = 1;
• Assignment Operator add to other
operators.
• For examples, The addition assignment
operator (+=) adds a value to a variable.
• Example: int a = 1;
a+= 5; // a= 1+5;
All Assignment Operators
Operator Example Same As
+= a += 5 a=a+5
-= a -= 5 a=a-5
*= a *= 5 a=a*5
/= a /= 5 a=a/5
%= a %= 5 a=a%5
C# Math
• The C# Math class has many methods
that allows you to perform mathematical
tasks on numbers.
• Math.Max(a,b)
The Math.Max(a,b) method can be used to
find the highest value of a and b. Example:
Math.Max(5, 10);
• Math.Min(a,b)
The Math.Min(a,b) method can be used to
find the lowest value of of a and b.Example:
Math.Min(5, 10);
C# Math
• Math.Sqrt(a)
The Math.Sqrt(a) method returns the square
root of x. Example: Math.Sqrt(64);
• Math.Abs(a)
The Math.Abs(a) method returns the
absolute (positive) value of x. Example:
Math.Abs(-4.7);
• Math.Round()
Math.Round() rounds a number to the
nearest whole number. Example:
Math.Round(9.99);
C# Strings
• Strings are used for storing text.
• A string variable contains a collection of
characters surrounded by double quotes,.
• Example: string greeting = "Hello";
• A string variable can contain many words.
• Example: string greeting = "Nice to meet
you!";
String Length
• A string in C# is actually an object, which
contain properties and methods that can
perform certain operations on strings.
• For example, the length of a string can be
found with the Length property:
string txt =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Console.WriteLine("The length of the txt
string is: " + txt.Length);
Output: The length of the txt string is: 26
String Methods
• There are many string methods available,
for example ToUpper() and ToLower(),
which returns a copy of the string
converted to uppercase or lowercase.
• Syntax:
string txt = "Hello World";
Console.WriteLine(txt.ToUpper());
// Outputs "HELLO WORLD"
Console.WriteLine(txt.ToLower());
// Outputs "hello world"
String Concatenation
• The + operator can be used between strings to
combine them. This is called concatenation.
• Example:
string firstName = "John ";
string lastName = " Doe";
string aname = firstName + lastName;
Console.WriteLine(aname);
//Output: John Doe
string cname = string.Concat(firstName,
lastName);
Console.WriteLine(cname);
//Output: John Doe
String Interpolation
• Another option of string concatenation, is
string interpolation, which substitutes
values of variables.
• Note that you do not have to worry about
spaces, like with concatenation.
• Example:
string firstName = "John";
string lastName = "Doe";
string name = $"My full name is:
{firstName} {lastName}";
Console.WriteLine(name);
//Output: My full name is: John Doe
Access Strings
• We can access the characters in a string by
referring to its index number inside square
brackets [].
• Prints the first character in myString.
string myString = "Hello";
Console.WriteLine(myString[0]); // Outputs: "H"
• We can also find the index position of a
specific character in a string, by using the
IndexOf() method.
• Example:string myString = "Hello";
Console.WriteLine(myString.IndexOf("e"));
// Outputs "1"
Strings - Special Characters
(1)
• Example: string txt = "We are the so-
called "Vikings" from the north.";
• The above example, generate an error
because strings must be written within
quotes, C# will misunderstand this string.
• The solution to avoid this problem, is to
use the backslash escape character (\) .
Escape character Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash
Strings - Special Characters (2)
• Example 1:
string txt = "We are the so-called \"Vikings\"
from the north.";
Console.WriteLine(txt);
//Output: We are the so-called "Vikings" from
the north.
• Example 2:
string txt = "It\'s alright.";
Console.WriteLine(txt);
//Output: It's alright.
C# Booleans
• A boolean type is declared with the bool
keyword and can only take the values true
or false.
• Example:
bool isCSharpFun = true;
bool isBroccoliTasty = false;
Console.WriteLine(isCSharpFun);
// Outputs True
Console.WriteLine(isBroccoliTasty);
// Outputs False
C# Conditions Statements
• C# has the following conditional
statements:
1. Use if to specify a block of code to be
executed, if a specified condition is true
2. Use else to specify a block of code to be
executed, if the same condition is false
3. Use else if to specify a new condition to
test, if the first condition is false
4. Use switch to specify many alternative
blocks of code to be executed
If Statement (1)
• If statement to specify a block of C# code
to be executed if a condition is True.
• Syntax:
if (condition)
{
// Code to be executed if the condition is True
}
• Example 1:
if (10 > 5)
{
Console.WriteLine("10 is greater than 5");
}
If Statement (2)
• Example 2:
int a = 10;
int b = 5;
if (a > b)
{
Console.WriteLine("a is greater than b");
}
// Output: a is greater than b
If ... Else Statement (1)
• The else statement to specify a block of code
to be executed if the condition is False.
• Syntax:
if (condition)
{
// Code to be executed if the condition is True
}
else
{
// Code to be executed if the condition is False
}
If ... Else Statement (2)
• Example:
int age = 10;
if (age >= 18)
{
Console.WriteLine("Eligible to Vote.");
}
else
{
Console.WriteLine("Not eligible to Vote.");
}
// Outputs: Not eligible to Vote.
Else If Statement (1)
• The else if statement to specify a new
condition if the first condition is False.
• Syntax:
if (condition1)
{
// Code to be executed if condition1 is True
}
else if (condition2)
{
// Code to be executed if the condition1 is false and condition2 is
True
}
else
{
//Code to be executed if the condition1 is false and condition2 is
False
}
Else If Statement (2)
• Example:
int time = 22;
if (time < 10)
{
Console.WriteLine("Good morning.");
}
else if (time < 20)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
// Outputs: Good evening.
Short Hand If...Else (Ternary
Operator 1)
• The short-hand if else, which is known as
the ternary operator because it consists of
three operands. It can be used to replace
multiple lines of code with a single line. It
is often used to replace simple if else
statements.
• Syntax:
variable = (condition) ?
expressionTrue : expressionFalse;
Short Hand If...Else (Ternary Operator 2)
• Example:
int age = 20;
string result = (age >= 18) ?
"Eligible to Vote." : "Not eligible to
Vote.";
Console.WriteLine(result);
// Output: Eligible to Vote.
Switch Statements (1)
• The switch statement to select one of
many code blocks to be executed.
• Syntax:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
Switch Statements (2)
• Example:
int day = 4;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
}
C# Loops
• Loops can execute a block of code as long
as a specified condition is reached.
• There are many loops in C# such as for
loop, while loop, do while loop etc. Details
about these are given as follows:
1. While Loop
2. Do...While loop
3. For Loop
4. Foreach Loop
While Loop
• The while loop continuously executes one or
more statements as long as the loop condition is
satisfied.
• If the loop condition is true, the body of the for
loop is executed. Otherwise, the control flow
jumps to the next statement after the while loop.
• The while keyword is used to create while loop
in C#. The syntax for while loop is:
while (condition)
{
/* body of while will be executed if the
condition is true*/
}
While Loop Example
int i=1;
while (i<=5)
{
Console.WriteLine("Iteration: "+ i);
i++;
}
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Do...While loop
• The do and while keyword is used to create a
do...while loop. It is similar to a while loop,
however there is a major difference between
them.
• In while loop, the condition is checked before the
body is executed.
• It is the exact opposite in do...while loop, i.e.
condition is checked after the body is executed.
• The syntax for do...while loop is,
do
{
// body of do while loop
} while (condition);
Do...While loop Example
int i=6;
do
{
Console.WriteLine("Iteration: "+ i);
i++;
}while (i<=5);
Output:
Iteration: 6
• This is why, the body of do...while loop will
execute at least once irrespective to the
condition.
For Loop
• The for loop executes a block of statements repeatedly
until the specified condition returns false.
• The for keyword is used to create for loop in C#. The
syntax for for loop is:
for (Initializer; condition; iterator)
{
// body of for loop
}
• Initializer: The initializer section is used to initialize a
variable that will be local to a for loop and cannot be
accessed outside loop.
• Condition: The condition is a boolean expression that
will return either true or false.
• Iterator: The iterator defines the incremental or
decremental of the loop variable.
For loop Example
for (int i=1; i<=5; i++)
{
Console.WriteLine("Iteration: "+ i);
}
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Foreach Loop
• There is also a foreach loop, which is used
exclusively to loop through elements in an
array.
• The foreach keyword is used to create foreach
loop in C#. The syntax for foreach loop is:
foreach (type variableName in arrayName)
{
// code block to be executed
}
Foreach Loop Example
string[] fruits = {"Apple", "Orange",
"Grapes", "Mango"};
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Output:
Apple
Orange
Grapes
Mango
C# Break
• The break statement can also be used to jump out of a
loop.
• This example jumps out of the loop when i is equal to 2:
for (int i = 0; i < 10; i++)
{
if (i == 2)
{
break;
}
Console.WriteLine("Iteration: "+ i);
}
• Output:
Iteration: 0
Iteration: 1
C# Continue
• The continue statement breaks one iteration (in
the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
• This example skips the value of 2
for (int i = 1; i <= 5; i++)
{
if (i == 2) Output:
Iteration:
{ O
1
continue;
Iteration:
} 3
Console.WriteLine("Iteration: "+i);Iteration:
} 4
Iteration:
C# Arrays
• Arrays are used to store multiple values in a
single variable, instead of declaring
separate variables for each value which is
also known as single dimension arrays.
• To declare an array, define the variable type
with square brackets:
• Syntax:
1. DateType[] variable_name={};
2. DateType[] variable = new
DateType[length] ;
3. DateType[] variable;
variable = new DateType[] {};
C# Arrays Examples
Example1:
string[] fruits = {"Apple", "Orange", "Grapes"};
Console.WriteLine(fruits[0]);
Output: Apple
Example2:
string[] fruits;
fruits = new string[] {"Apple", "Orange", "Grapes"};
Console.WriteLine(fruits[2]);
Output: Grapes
Example3:
string[] fruits = new string[2];
fruits[0] = Mango; // Count more than 2 is not allowed
Console.WriteLine(fruits[0]);
Output: Mango
Loop Through an Array (1)
• We can loop through the array elements with the
for loop, and use the Length property to specify
how many times the loop should run.
• There is also a foreach loop, which is used
exclusively to loop through elements in an array.
• The following example outputs all elements in the
days array:
string[] days = {"Monday", "Tuesday",
"Wednesday", "Thursday", "Friday"};
Output:
for (int i = 0; i < days.Length; i++) Monday
{ Tuesday
Console.WriteLine(days[i]); Wednesday
Thursday
}
Friday
Loop Through an Array (2)
int[] days = {1, 2, 3, 4, 5};
foreach (int i in days)
{
Console.WriteLine("Day: " +i);
}
Output:
Day: 1
Day: 2
Day: 3
Day: 4
Day: 5
Sort an Array (1)
• There are many array methods available, for example
Sort(), which sorts an array alphabetically or in an
ascending order
Example 1:
int[] days = {4, 2, 1, 5, 3};
Array.Sort(days);
foreach (int i in days)
{
Console.WriteLine("Day: " +i);
}
Output:
Day: 1
Day: 2
Day: 3
Day: 4
Day: 5
Example 2: Sort an Array (2)
string[] fruits = {"Orange", "Grapes",
"Mango","Apple"};
Array.Sort(fruits);
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Output:
Apple
Grapes
Mango
Orange
• Other useful array methods, such as Min, Max, and
Sum, can be found in the System.Linq namespace
and apply only to integer.
System.Linq Namespace
using System;
using System.Linq;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int[] myNumbers = {5, 1, 8, 9};
Console.WriteLine(myNumbers.Max()); //O/p: 9
Console.WriteLine(myNumbers.Min()); //O/p: 1
Console.WriteLine(myNumbers.Sum());//O/p: 23
}
}
}
Multidimensional Arrays
• If we want to store data as a tabular form,
like a table with rows and columns, you need
to get familiar with multidimensional arrays.
• A multidimensional array is basically an
array of arrays.
• Arrays can have any number of dimensions.
The most common are two-dimensional
arrays (2D).
• Syntax:
DateType[,] variable_name={{},{}};
• Example:
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
Multidimensional Arrays Examples
Example 1:
int[,] numbers = { {1, 4}, {3, 6} };
foreach (int i in numbers)
{
Console.WriteLine(i);
}
Console.WriteLine(numbers[0, 0]);
Output:
1
4
3
6
1
Multidimensional Arrays Examples
• We have to use GetLength() instead of Length
to specify how many times the loop should
run.
Example 2:
int[,] numbers = { {1, 4}, {3, 6} };
for (int i = 0; i < numbers.GetLength(0); i++)
{
for (int j = 0; j < numbers.GetLength(1); j++)
{
Console.WriteLine(numbers[i, j]);
}
}
C# Methods (1)
• A method is a block of code which only
runs when it is called.
• We can pass data, known as parameters,
into a method.
• Methods are used to perform certain
actions, and they are also known as
functions.
• C# provides some pre-defined methods,
which you already are familiar with, such
as Main(), but we can also create our own
methods to perform certain actions.
C# Methods(2)
• Syntax:
static void Method_Name()
{
// code to be executed
}
• Method_Name() is the name of the method
• static means that the method belongs to
the certain class and not an object of that
class.
• void means that this method does not have
a return value.
C# Methods(3)
• Example 1:
class Program
{
static void MyMethod() // Method definition
{
Console.WriteLine("I just got executed!");
}
static void Main(string[] args)
{
MyMethod(); // Method Call
}
}
Output: I just got executed!
Methods Parameters and Arguments
static void ListCountry(string country)
{
Console.WriteLine(country );
}
static void Main(string[] args)
{
ListCountry("India");
ListCountry("US");
ListCountry("Germany");
}
Output:
India
US
Germany
Default Parameter Value - Method
• We can also use a default parameter value, by
using the equals sign (=).
• If we call the method without an argument, it
uses the default value ("Indian").
• Example:
static void ListCountry(string country = "Indian")
{
Console.WriteLine("He/She is an/a "+country);
}
static void Main(string[] args)
{
Output:
ListCountry("Sweden"); He/She is an/a Sweden
ListCountry(); He/She is an/a Indian
ListCountry("American"); He/She is an/a
} American
Return Values - Method (1)
• we used the void keyword in all examples,
which indicates that the method should
not return a value.
• If you want the method to return a value,
you can use data type (such as int or
double) instead of void, and use the
return keyword inside the method
• Syntax:
static int Method_Name(int x)
{
return DType_variable/Value;
}
Return Values - Method (1)
Example:
static int MyMethod(int x)
{
return 5 + x;
}
static void Main(string[] args)
{
Console.WriteLine(MyMethod(3));
int z =MyMethod(2);
Console.WriteLine(z);
}
Output:
8
7
C# Method Overloading
• With method overloading, multiple methods can have
the same name with different parameters.
• Example:
static int PlusMethod(int x, int y)
{ return x + y; }
static double PlusMethod(double x, double y)
{ return x + y; }
static void Main(string[] args)
{
int no1 = PlusMethod(10, 5);
double no2 = PlusMethod(4.3, 6.26);
Console.WriteLine("Int: " + no1 + " Double: " + no2);
}
Output: Int: 15 Double: 10.56
C# OOP
• OOP stands for Object-Oriented Programming.
• Procedural programming is about writing
procedures or methods that perform operations on
the data, while object-oriented programming is
about creating objects that contain both data and
methods.
• Object-oriented programming has several
advantages over procedural programming:
1. OOP is faster and easier to execute
2. OOP provides a clear structure for the programs
3. OOP makes it possible to create full reusable
applications with less code and shorter
development time
C# OOP - Class & Object (1)
• For examples,
Class: Class: Class:
Fruits Days Chairs
Objects: Objects: Objects:
Apple Monday Wooden
Orange Tuesday Plastic
Mango Wednesday Metal
Cherry Thursday Plywood
• Everything in C# is associated with classes and
objects, along with its attributes and methods.
• For example: in real life, a car is an object. The
car has attributes, such as model and color, and
methods, such as drive and brake.
Class Example, with attributes and method:
C # O O P -C la s& O b ject(2 )
class Fruit
{
string color = "red";
public void Benefits() // method
{
Console.WriteLine("Benefits - Protect our hearts.");
}
static void Main(string[] args)
{
Fruit x= new Fruit(); //Object Declaration syntax
Console.WriteLine("Fruit Color: " +x.color);
x.Benefits();
}
}
Output:
Fruit Color: Red
Benefits - Protect our hearts.
C# Class Members
• Fields and methods inside classes are
often referred to as "Class Members".
• There are 4 types,
1. Without argument without return type.
2. With argument without return type.
3. Without argument with return type.
4. With argument with return type.
C# Class Members - Without
argument without return type
Example:
class Fruit
{
public void quote() // method
{
Console.WriteLine("An apple a day keeps the doctor away.");
}
static void Main(string[] args)
{
Fruit apple = new Fruit();
apple.quote();
}
}
Output:
An apple a day keeps the doctor away.
C# Class Members - With argument without
return type
Example:
class Fruit
{
public void quote(string name) // method
{
Console.WriteLine("An "+name+ " a day keeps the doctor away.");
}
static void Main(string[] args)
{
Fruit apple = new Fruit();
apple.quote("Apple");
}
}
Output:
An apple a day keeps the doctor away.
C# Class Members - Without
argument with return type
Example:
class Fruit
{
public string quote() // method
{
string txt = "An apple a day keeps the doctor away.";
return txt;
}
static void Main(string[] args)
{
Fruit apple = new Fruit();
string text = apple.quote();
Console.WriteLine(text);
}
}
Output:
An apple a day keeps the doctor away.
C# Class Members - With argument
with return type
Example:
class Fruit
{
public string quote(string name) // method
{
string txt = "An " +name+ " a day keeps the doctor away.";
return txt;
}
static void Main(string[] args)
{
Fruit apple = new Fruit();
string text = apple.quote("Apple");
Console.WriteLine(text);
}
}
Output:
An apple a day keeps the doctor away.
C# Constructors
• A constructor is a special method that is
used to initialize objects. The advantage
of a constructor, is that it is called when
an object of a class is created. It can be
used to set initial values for fields.
• The constructor name must match the
class name, and it cannot have a return
type (like void or int).
• The constructor is called when the object
is created
C# Constructors Example
Example:
class Fruit
{
public Fruit() // method
{
Console.WriteLine("Time and health are two precious assets that we
don't recognize and appreciate until they have been depleted.");
}
static void Main(string[] args)
{
Fruit apple = new Fruit();
Console.WriteLine("Have a great day!!!");
}
}
Output:
Time and health are two precious assets that we don't recognize and
appreciate until they have been depleted.
Have a great day!!
C# Access Modifiers
• By default, all members of a class is
Private.
Modifier Description
public The code is accessible for all classes
private The code is only accessible within the same class
protected Access to the members of the same class and its
derived classes
internal Access to the current assembly.
Encapsulation
• Encapsulation means protect important
data inside the class which we do not
want to be exposed outside the class.
• Encapsulation process means binding the
data members (variable, properties) and
member function (Methods) in a single
unit.
• Class is one of the best an example of an
encapsulation.
• Encapsulation hides private or unwanted
data from outside the class
class Encapsulation {
Encapsulation
private string Name = "Alex";
public string EmployeeName { // Property
get {
return Name;
}
set {
Name = value;
}
}
static void Main(string[] args) {
Encapsulation e = new Encapsulation();
string Name2 = e.EmployeeName;
Console.WriteLine("Employee Name: " + Name2);
Console.ReadLine();
}
}
Output: Employee Name: Alex
GET returns the value of the property field.
SET sets the value of the property field with the contents of the values.
C# Inheritance
• It is the mechanism in C# by which one
class is allowed to inherit the
features(fields and methods) of another
class.
⮚ Derived Class (child) - the class that
inherits from another class
⮚ Base Class (parent) - the class being
inherited from
• It is useful for code reusability: reuse
fields and methods of an existing class
when you create a new class
C# Inheritance
• Syntax:
class derived-class : base-class
{
// methods and fields
}
• To inherit from a class, use the : symbol.
• Types of Inheritance in C#:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance(Through Interfaces)
5. Hybrid Inheritance(Through Interfaces)
Single Inheritance
• In single inheritance, derived class inherit
the features of base class. In image below,
the class A serves as a base class for the
derived class B
Single
Inheritance
public class Employee
{ Single Inheritance
public float salary = 40000;
}
public class Programmer: Employee
{
public float bonus = 10000;
}
class TestInheritance
{
public static void Main(string[] args)
{
Programmer
= new Programmer();
Console.WriteLine("Salary: " + p1.salary);
Console.WriteLine("Bonus: " + p1.bonus);
Console.ReadLine();
}
}
Multilevel Inheritance
public class Employee {
public float salary = 40000;
}
public class Programmer: Employee {
public float bonus = 10000;
}
public class FEDeveloper: Programmer {
public float hike = 20000;
}
class TestInheritance{
public static void Main(string[] args)
{
Programmer p1 = new Programmer();
Console.WriteLine("Salary: " + p1.salary);
Console.WriteLine("Bonus: " + p1.bonus);
Console.WriteLine("Bonus: " + p1.hike);
Console.ReadLine();
}
}
Multilevel Inheritance
• In Multilevel Inheritance, a derived class will be
inheriting a base class and as well as the derived
class also act as the base class to other class.
• In below image, class A serves as a base class for
the derived class B, which in turn serves as a
base class for the derived class C
A
Multilevel
Inheritance
B
C
Hierarchical Inheritance
• In Hierarchical Inheritance, one class serves as a
superclass (base class) for more than one
subclass.
• In below image, class A serves as a base class for
the derived class B, C, and D.
A
B C D
Hierarchical
Inheritance
Hierarchical Inheritance
public class Employee {
public float salary = 40000;
}
public class Programmer: Employee {
public float bonus = 10000;
}
public class HR: Employee {
public float hike = 5000;
}
class TestInheritance{
public static void Main(string[] args)
{
Programmer p1 = new Programmer(); Hr p2 = new Hr();
Console.WriteLine("Salary: " + p1.salary);
Console.WriteLine("Bonus: " + p1.bonus);
Console.WriteLine("Bonus: " + p2.salary);
Console.WriteLine("Bonus: " + p2.hike);
Console.ReadLine();
}
}
Multiple Inheritance Using Interfaces
• In Multiple inheritance, one class can have more
than one superclass and inherit features from all
parent classes.
• C# does not support multiple inheritance with
classes.
• In C#, we can achieve multiple inheritance only
through Interfaces. In the image below, Class C
is derived from interface A and B.
A B
C Multiple
Inheritance
Multiple Inheritance Using Interfaces
Syntax:
public interface Interface1
{
void Test();
}
public interface Interface2
{
void Test();
}
public class MultipleInheritanceTest : Interface1, Interface2
{
}
Multiple Inheritance Using Interfaces
Example
interface Car{ void Drive(); } // base
interface Bus{ void Drive(); }// base
class Demo : Car, Bus // derived
{
void Car.Drive(){
Console.WriteLine("Drive Car");
}
void Bus.Drive(){
Console.WriteLine("Drive Bus");
}
static void Main() {
Demo DemoObject = new Demo();
((Car)DemoObject).Drive();
((Bus)DemoObject).Drive();
Console.Read();
}
}
Hybrid Inheritance Using Interfaces
• It is a mix of two or more of the above types of
inheritance.
• Since C# doesn’t support multiple inheritance
with classes, the hybrid inheritance is also not
possible with classes.
• In C#, we can achieve hybrid inheritance only
through Interfaces.
A
B C
Hybrid
D
Inheritance
C# Abstraction
• Data abstraction is the process of hiding certain
details and showing only essential information to
the user.
• Abstraction can be achieved with either abstract
classes or interfaces.
• Abstract class: is a restricted class that cannot be
used to create objects (to access it, it must be
inherited from another class).
• Abstract method: can only be used in an abstract
class, and it does not have a body. The body is
provided by the derived class (inherited from).
• The abstract keyword is used for classes and
methods
C# Abstraction Examples(1)
• In C#, we cannot create objects of an
abstract class. We use the abstract
keyword to create an abstract class. For
example,
// create an abstract class
abstract class Language {
// fields and methods
}
// try to create an object Language
// throws an error
Language obj = new Language();
C# Abstraction Examples (2)
• An abstract class can have both abstract
methods (method without body) and non-
abstract methods (method with the body).
For example,
abstract class Language {
// abstract method
public abstract void display1();
// non-abstract method
public void display2() {
Console.WriteLine("Non abstract method");
}
}
C# Abstraction Examples (3)
• As we cannot create objects of an abstract class, we
must create a derived class from it.
• So that we can access members of the abstract class
using the object of the derived class. For example,
abstract class Language {
public void display() {
Console.WriteLine("Non abstract method");
}
}
class Program : Language { // inheriting from abstract class
static void Main (string [] args) {
Program obj = new Program();// object of Program class
obj.display(); // access method of an abstract class
}
}
C# Abstraction Examples (4)
• A method that does not have a body is
known as an abstract method. We use the
abstract keyword to create abstract
methods. For example,
• public abstract void display();
• Here, display() is an abstract method. An
abstract method can only be present
inside an abstract class.
• When a non-abstract class inherits an
abstract class, it should provide an
implementation of the abstract methods.
C# Abstraction Examples (4)
abstract class Animal {
public abstract void makeSound(); // abstract method
}
class Dog : Animal { // inheriting from abstract class
// provide implementation of abstract method
public override void makeSound() {
Console.WriteLine("Bark Bark");
}
}
class Program {
static void Main (string [] args) {
Dog obj = new Dog(); // create an object of Dog class
obj.makeSound();
}
}
C# Interface
• In C#, an interface is similar to abstract
class. However, unlike abstract classes,
all methods of an interface are fully
abstract (method without body).
• We use the interface keyword to create an
interface. For example,
interface IPolygon {
void calculateArea(); // method without
body
}
Implementing an Interface
• We cannot create objects of an interface.
• To use an interface, other classes must implement it.
• Same as in C# Inheritance, we use : symbol to implement an
interface. For example,
interface IPolygon { // method without body
void calculateArea(int l, int b);
}
class Rectangle : IPolygon { // implementation of methods inside 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);
}
}
Implementing Multiple Interfaces
interface IPolygon // method without body
void calculateArea(int a, int b);
}
interface IColor {
void getColor();
}
class Rectangle : IPolygon, IColor { // implements two interface
// 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();
}
}
C# - Polymorphism
• The word polymorphism means having many forms. In
object-oriented programming paradigm, polymorphism is
often expressed as 'one interface, multiple functions'.
• There are two types of polymorphism in C#. They are as
follows:
1. Static Polymorphism / Compile-Time Polymorphism / Early
Binding
2. Dynamic Polymorphism / Run-Time Polymorphism / Late
Binding.
Real-Time Examples of Polymorphism:
One Interface, Different Behavior(function):
⮚ In Shopping Mall, behave like a customer
⮚ In Class Room, behave like a student
⮚ In Bus, behave like a passenger.
⮚ In Home, behave like a son.
Static Polymorphism
Static Polymorphism
• The mechanism of linking a function with an object during
compile time is called early binding. It is also called static
binding. C# provides two techniques to implement static
polymorphism.
• They are −
✔ Function overloading
✔ Operator overloading
• Function Overloading
• We an have multiple definitions for the same function name in the
same scope. The definition of the function must differ from each
other by the types and/or the number of arguments in the argument
list. You cannot overload function declarations that differ only by
return type.
• The following example shows using function print() to print different
data types
Function Overloading example
class Printdata {
void print(int i) {
Console.WriteLine("Printing int: {0}", i );
}
void print(double f) {
Console.WriteLine("Printing float: {0}" , f);
}
void print(string s) {
Console.WriteLine("Printing string: {0}", s);
}
static void Main(string[] args) {
Printdata p = new Printdata();
p.print(5); // Call print to print integer
p.print(500.263); // Call print to print float
p.print("Hello C++"); // Call print to print string
}
}
C# - Operator Overloading
• We can redefine or overload most of the built-in
operators available in C#.
• Overloaded operators are functions with special
names the keyword operator followed by the
symbol for the operator being defined.
• Similar to any other function, an overloaded
operator has a return type and a parameter list.
• Overloadable Operators:
+, -, *, /, %.!, ~, ++, --, ==, !=, <, >, <=, >=
• Non-Overloadable Operators:
+=, -=, *=, /=, %= : The assignment operators
cannot be overloaded.
Operator Overloading Example
class Example{ class Program
public int num; {
public Example(){ static void Main(string[] args)
num = 0; {
} Example num = new
public Example(int n){ Example(200);
num = n; Example num1 = new
} Example(300);
public static Example operator
Example num2 = new
+(Example e1, Example e2){
Example();
Example e3 = new Example();
e3.num = e1.num + e2.num;
num2 = num + num1;
return e3; num.display();
} num1.display();
public void display(){ num2.display();
Console.WriteLine("{0}", Console.Read();
num); }
}
}
}
Dynamic Polymorphism
• C# allows us to create abstract classes that are used to
provide partial class implementation of an interface.
Implementation is completed when a derived class
inherits from it. Abstract classes contain abstract
methods, which are implemented by the derived class.
The derived classes have more specialized functionality.
• Here are the rules about abstract classes −
⮚ we cannot create an instance of an abstract class
⮚ we cannot declare an abstract method outside an
abstract class
⮚ When a class is declared sealed, it cannot be
inherited, abstract classes cannot be declared sealed.
Dynamic Polymorphism Example
abstract class Shape { class RectangleTester {
public abstract int area(); static void Main(string[]
} args) {
class Rectangle: Shape { Rectangle r = new
private int length; Rectangle(10, 7);
private int width; double a = r.area();
public Rectangle( int a = 0,
int b = 0) { Console.WriteLine("Area:
length = a; {0}",a);
width = b; Console.ReadKey();
}
}
public override int area () {
}
Console.WriteLine("Rectangle
class area :");
return (width * length);
}
}
Dynamic polymorphism - Implemented by abstract classes and virtual functions
class Shape {
public override int area() {
protected int width, height;
Console.WriteLine("Triangle class
public Shape( int a = 0, int b = 0) { area :");
width = a; return (width * height / 2);
height = b; }
} }
public virtual int area() { class Caller {
Console.WriteLine("Parent class area :");
public void CallArea(Shape sh) {
return 0;
int a = sh.area();
}
Console.WriteLine("Area: {0}", a);
}
}
class Rectangle: Shape {
}
public Rectangle( int a = 0, int b = 0):
base(a, b) {
class Tester {
} static void Main(string[] args) {
public override int area () { Caller c = new Caller();
Console.WriteLine("Rectangle class Rectangle r = new Rectangle(10, 7);
area :"); Triangle t = new Triangle(10, 5);
return (width * height); c.CallArea(r);
} c.CallArea(t);
} Console.ReadKey();
class Triangle: Shape { }
public Triangle(int a = 0, int b = 0): base(a, b) }
{}
C# Exception Handling
• An exception is defined as an event that occurs during the execution of a
program that is unexpected by the program code. The actions to be performed
in case of occurrence of an exception is not known to the program. In such a
case, we create an exception object and call the exception handler code.
• C# exception handling is built upon four keywords: try, catch, finally, and
throw.
• try − A try block identifies a block of code for which particular exceptions is
activated. It is followed by one or more catch blocks.
• catch − A program catches an exception with an exception handler at the
place in a program where you want to handle the problem. The catch keyword
indicates the catching of an exception.
• finally − The finally block is used to execute a given set of statements,
whether an exception is thrown or not thrown. For example, if you open a file,
it must be closed whether an exception is raised or not.
• throw − A program throws an exception when a problem shows up. This is
done using a throw keyword.
C# Exception Handling
SYNTAX:
try {
// statements causing exception
} catch( ExceptionName e1 ) {
// error handling code
} catch( ExceptionName e2 ) {
// error handling code
} catch( ExceptionName eN ) {
// error handling code
} finally {
// statements to be executed
}
C# Exception Handling Example
class DivNumbers {
int result;
DivNumbers() { result = 0; }
public void division(int num1, int num2) {
try {
result = num1 / num2;
} catch (Exception ex) {
Console.WriteLine("Exception caught: {0}", ex);
} finally {
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args) {
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
C# File Handling
• File Handling involves management of
files. Files are a collection of data that is
stored in a disk with a name and a
directory path. Files contain input as well
as output streams that are used for reading
and writing data respectively.
• The System.IO Namespace has various
classes and types that allow reading of files
and writing to files. Some of the classes in
this namespace are given as follows:
C# File Handling
• FileStream: This class provides a Stream for a
file, supporting both synchronous and
asynchronous read and write operations.
• StreamReader: This class implements a
TextReader that reads characters from a byte
stream in a particular encoding.
• StreamWriter: This class implements a TextWriter
for writing characters to a stream in a particular
encoding.
• TextReader: This class represents a reader that
can read a sequential series of characters.
• TextWriter: This class represents a writer that can
write a sequential series of characters. This class
is abstract.
C# File Handling Example
using System;
using System.IO;
namespace FileHandlingDemo
{
public class Example
{
public static void Main(string[] args)
{
FileStream fi = new FileStream("e:\\file.txt", FileMode.OpenOrCreate);
fi.WriteByte(12);
fi.WriteByte(6);
fi.WriteByte(30);
fi.Close();
FileStream fo = new FileStream("e:\\file.txt", FileMode.OpenOrCreate);
int i = 0;
Console.WriteLine("The contents of the file are:");
while ((i = fo.ReadByte()) != -1)
{
Console.WriteLine(i);
}
fo.Close();
}
}
}
C# File Handling Example
using System;
using System.IO;
namespace FileHandlingDemo
{
public class Example
{
public static void Main(string[] args)
{
FileStream f1 = new FileStream("e:\\file.txt", FileMode.OpenOrCreate);
StreamWriter s1 = new StreamWriter(f1);
s1.WriteLine("File Handling in C#");
s1.Close();
f1.Close();
FileStream f2 = new FileStream("e:\\file.txt", FileMode.OpenOrCreate);
StreamReader s2 = new StreamReader(f2);
string data = s2.ReadLine();
Console.WriteLine("The data in the file is as follows:");
Console.WriteLine(data);
s2.Close();
f2.Close();
}
}
}
Enumeration
● An enum is a special "class" that represents a
group of constants (unchangeable/read-only
variables).
● To create an enum, use the enum keyword
(instead of class or interface), and separate
the enum items with a comma.
enum Color
{
Red,
Green,
Blue
}
Enumeration
class Program
{
enum WeekDays
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
static void Main(string[] args)
{
int myNum = (int) WeekDays.April;
Console.WriteLine(myNum);
}
}
Enumeration
using System;
namespace MyApplication
{
class Program
{
enum Categories
{
Electronics = 1,
Food = 5,
Automotive = 6,
Arts = 10,
BeautyCare = 11,
Fashion = 15,
WomanFashion = 15
}
static void Main(string[] args)
{
var tools = Enum.GetValues(typeof(Categories));
foreach (Categories tool in tools)
Console.WriteLine($"{tool} ({tool:D})");
}
}