0% found this document useful (0 votes)
56 views106 pages

C# Material

This document provides a comprehensive introduction to C# and .NET, covering essential topics such as the structure of C# applications, naming conventions, data types, and object-oriented programming principles. It includes practical examples and guidelines for writing C# code, as well as instructions for creating console applications using Visual Studio. Additionally, it emphasizes the importance of formatting output and reading user input in C# programs.

Uploaded by

20891a6702
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)
56 views106 pages

C# Material

This document provides a comprehensive introduction to C# and .NET, covering essential topics such as the structure of C# applications, naming conventions, data types, and object-oriented programming principles. It includes practical examples and guidelines for writing C# code, as well as instructions for creating console applications using Visual Studio. Additionally, it emphasizes the importance of formatting output and reading user input in C# programs.

Uploaded by

20891a6702
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/ 106

C#

C# .Net
(Simplified)

SRINIVAS GARAPATI

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, AMEERPET, HYDERABAD
Contact for Online Classes: +91 – 911 955 6789 / 7306021113
www.ameerpettechnologies.com

Contents

S No Topic Page Num


01 Introduction to C# 02
02 Structure of C# application 03
03 C# Naming conventions 06
04 Variables and Data types 08
05 Formatting Output 12
06 Reading input using Console.ReadLine() 14
07 Operators in C# 16
08 Control Statements 25
09 Object Oriented programming 37
10 Static and Instance Members 40
11 this 48
12 Access modifiers 50
13 Encapsulation 52
14 this() 54
15 Inheritance 55
16 base() 60
17 Polymorphism 61
18 Sealed classes 64
19 Abstraction 65
20 Interfaces 68
21 Multiple Inheritance 69
22 Objects - Relations 71
23 Arrays 74
24 Array class 77
25 Strings 78
26 String Immutability and Interpolation 80
27 StringBuilder class 81
28 Exception Handling 83
29 Multi – threading 94
30 Stream IO 101

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 1


www.ameerpettechnologies.com

C# .Net
Introduction:
• C# is a simple & powerful object-oriented programming language developed by
Microsoft.
• .NET is an open-source.
• It can be used to create console applications, GUI applications, web applications.
• .NET applications development under Visual Studion IDE.
• Using Core concepts of C#,
o We develop Desktop applications.
• Using ADO. Net,
o we can connect with Databse(SQL server) either from Desktop application or A
Web application. M
• Using .Net technologies (ASP .NET) E
o We develop Web based applications. E
• Using Frameworks (MVC) R
o We achieve Rapid applications development. P
E
Essentials: T
• .Net framework contains a large number of class libraries known as Framework Class T
Library (FCL). E
• The software programs written in .NET are executed in the execution environment, which C
is called CLR (Common Language Runtime). H
N
CLR: (Common Language Runtime) O
• .NET code compiled into MSIL(Microsoft intermediate language code). L
• MSIL is platform(OS) independent O
• .NET CLR is a virtual machine that converts MSIL code into native code of the machine. G
This code is platform-dependent. I
• Native code run on compatible platform. E
S

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 2


www.ameerpettechnologies.com

Structure of C# Program

What is a Console Application?


• A console application is an application that can be run in the command prompt.
• Now, let’s understand the Basic Structure of the C# Program using a Console
Application.

Now we are going to use Visual Studio to create a Console-Type Project.


Step1: First, open Visual Studio 2022 (the latest version at this point in time) and then click on
the Create a New Project option as shown in the below image.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 3


www.ameerpettechnologies.com

Step2:
• The next step is to choose the project type as a Console Application.
• Type Console in the search bar and you will see different types of console applications
using C#, VB etc.
• We need to select Console App (.NET Framework) using C# Language
• Click on the Next button as shown in the below image.

Step3
• The next step is to configure the new project.
• Here, I am providing the name MyFirstProject to both project and solution.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 4


www.ameerpettechnologies.com

Once you click on the Create button, visual studio will create the Console Application with the
following structure.

Step4: Now let’s write our code which will be used to display the message “Welcome to C#.NET”
in the console window.
using System;
namespace MyFirstProject
{
internal class Program
{
static void Main()
{
Console.WriteLine("Welcome to C#.NET");
Console.ReadKey();
}
}
}

Step5: The next step is to run the .NET Application.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 5


www.ameerpettechnologies.com

C# naming conventions

Use PascalCase for class names, method names, and property names.

public class CustomerOrder


{
public void PlaceOrder(string orderDetails)
{
// Place order implementation here
}

public string OrderNumber { get; set; } A


} M
E
E
Use camelCase for variable and parameter names. R
P
public void CalculateTotalCost(double productCost, int quantity) E
{ T
double totalCost = productCost * quantity; T
Console.WriteLine($"The total cost is {totalCost}"); E
} C
H
N
Avoid using single-letter names for variables or parameters unless the meaning is O
obvious. L
O
// Not recommended G
public void CalculateTotalCost(double p, int q) I
{ E
double t = p * q; S
Console.WriteLine($"The total cost is {t}");
}

// Recommended
public void CalculateTotalCost(double productCost, int quantity)
{
double totalCost = productCost * quantity;
Console.WriteLine($"The total cost is {totalCost}");
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 6


www.ameerpettechnologies.com

Avoid using reserved keywords as names for variables, classes, or other program
elements.
// Not recommended
public class int
{
public void doSomething(string @string)
{
int @int = Convert.ToInt32(@string);
}
}

// Recommended
public class MyClass
{
public void DoSomething(string inputString)
{
int result = Convert.ToInt32(inputString);
}
}

Use meaningful prefixes for variables that indicate their type or purpose.
public void SetCustomerName(string strCustomerName)
{
// Implementation here
}

Do not use spaces in names, and avoid using special characters except for underscores.
// Not recommended
public class Customer Order
{
public string Order Number { get; set; }
}

// Recommended
public class CustomerOrder
{
public string OrderNumber { get; set; }
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 7


www.ameerpettechnologies.com

Variables and Data types


Variable: Identity given to memory location.
or
Named memory location

Syntax:
datatype identity = value;

Examples:
String name = “Amar”;
int age = 23;
char gender = ‘M’;
bool married = false;
double salary = 35000.00;

Declaration, Assignment, Update and Initialization of Variable:


1. Declaration: creating a variable without any value.
int a ;
2. Assignment: Storing a value into variable which is already declared.
a = 10 ;
3. Modify: Increase or Decrease the value of variable.
a=a+5;
4. Initialization: Assigning value at the time of declaration
int b = 20 ;

Identifier rules:
• Identifier is a name given to class, method, variable etc.
• Identifier must be unique
• Identifier is used to access the member.

Rules to create identifier:


1. Identifier allows [A-Z] or [a-z] or [0-9], and underscore(_) or a dollar sign ($).
2. Spaces not allowed in identifier.
3. Identifier should not start with digit.
4. Identifier can starts with special symbol.
5. We can't use the Java reserved keywords as an identifier.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 8


www.ameerpettechnologies.com

Integer data types:


int a = 10;
int b = 20;
int c = a + b;
Console.WriteLine(c); // Output: 30

Floating-point data types:


float f = 3.14f;
double d = 1.23456789;
double result = d * 2;
Console.WriteLine(result); // Output: 2.46913578

Boolean data type:


bool isTrue = true;
bool isFalse = false;
if (isTrue && !isFalse)
Console.WriteLine("Both conditions are true.");
else
Console.WriteLine("At least one condition is false.");

Character data type:


char ch = 'A';
char dollar = '$';
Console.WriteLine(ch); // Output: A
Console.WriteLine(dollar); // Output: $

String data type:


string name = "Amar";
string message = "Hello, " + name + "!";
Console.WriteLine(message); // Output: Hello, Amar!

DateTime data type:


DateTime now = DateTime.Now;
Console.WriteLine(now); // Output: 4/9/2023 2:45:11 PM

Object data type:


object obj2 = "hello";
object obj3 = DateTime.Now;
Console.WriteLine(obj2); // Output: hello
Console.WriteLine(obj3); // Output: 4/9/2023 2:45:11 PM

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 9


www.ameerpettechnologies.com

Character data type: Character type variable is used to store alphabets, digits and symbols.
class Code
{
public static void Main() {
char x = 'A';
char y = '5';
char z = '$';
Console.WriteLine("x val : " + x + "\ny val : " + y + "\nz val : " + z);
}
} A
Note: We must represent Character with Single Quotes in Java M
E
E
ASCII : Representation of each character of language using constant integer value.
R
A-65 a-97 0-48 *-34
P
B-66 b-98 1-49 #-35 E
… …. .. $-36 T
… …. .. …
T
… …. .. …
E
Z-90 z-122 9-57 … C
H
N
Type casting: O
• Conversion of data from one data type to another data type. L
• Type casting classified into O
o Implicit cast: Auto conversion of data from one type to another type. G
o Explicit cast: Manual conversion of data from one type to another type. I
E
Convert Character to Integer: this conversion happens implicitly when we assign character to S
integer type.
class Code
{
public static void Main() {
char ch = 'A' ;
int x = ch ;
Console.WriteLine("x value : " + x);
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 10


www.ameerpettechnologies.com

Convert Integer to Character: this conversion must be done manually


class Code
{
public static void Main() {
int x = 97 ;
char ch = (char)x ;
Console.WriteLine("ch value : "+ch);
}
}

Convert Upper case to Lower case Character:

class Code {
public static void Main() {
char up = 'A';
char lw = (char)(up+32);
Console.WriteLine("Result : " + lw);
}
}

Convert Digit to Number: We can convert character type digit into number as follows

class Code
{
public static void Main() {
char d = '5';
int n = d-48;
Console.WriteLine("Result : " + n);
}
}
Note: Type casting not required in above code as we are assigning value to integer variable.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 11


www.ameerpettechnologies.com

Formatting Output

Introduction: It is important to format the output before display the results to end user.
Proper formatting makes the user more understandable about program results.

We always display results in String format. To format the output, we concatenate the
values such as int, char, double, boolean with messages (string type) as follows:

Syntax Example
int + int = int 10 + 20 = 30
String + String = String “C#” + “Book” = C#Book
“10” + “20” = 1020
String + int = String “Book” + 1 = Book1
“123” + 456 = 123456
String + int + int = String “Sum = “ + 10 + 20 = Sum1020
String + (int + int) = String “Sum = “ + (10 + 20) = Sum30
String + double = String “Value = “ + 23.45 = Value = 23.45
String – int = Error

public class Code


{
public static void Main() {
int a=10;
Console.WriteLine(a);
}
}
Output: 10

public class Code


{
public static void Main() {
int a=10, b=20;
Console.WriteLine (a + “ , “ + b);
}
}
Output: 10, 20

public class Code


{
public static void Main() {
int a=10, b=20;
Console.WriteLine ("a = " + a);

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 12


www.ameerpettechnologies.com

Console.WriteLine ("b = " + b);


}
}
Output: a = 10
b = 20

public class Code


{
public static void Main() {
int a=10, b=20;
Console.WriteLine ("a = " + a + “ , “ + "b = " + b);
}
}
Output: a = 10, b = 20

public class Code


{
public static void Main() {
int a=10, b=20;
int c=a+b;
Console.WriteLine ("Sum of " + a + " and " + b + " is " + c);
}
}
Output: Sum of 10 and 20 is 30

public class Code


{
public static void Main() {
int a=10, b=20;
int c=a+b;
Console.WriteLine (a + " + " + b + " = " + c);
}
}
Output: 10+20=30

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 13


www.ameerpettechnologies.com

Reading input – Console.ReadLine()

Console.ReadLine():
• It is used to read input from the Console.
• ReadLine() method always returns the input in String format only.
• We need to convert that String into corresponding type.

Reading String:
using System;
public class Program
{
public static void Main()
{
Console.Write("Enter your name : ");
String name = Console.ReadLine();
Console.WriteLine("Hello " + name);
}
}

Reading integer:
using System;
public class Program
{
public static void Main()
{
Console.Write("Enter an integer : ");
String s = Console.ReadLine();
int n = Convert.ToInt32(s);
Console.WriteLine("Input number is : " + n);
}
}

Reading int, double and boolean:


using System;
public class Program
{
public static void Main()
{
Console.Write("Enter an integer : ");
int n = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter double : ");

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 14


www.ameerpettechnologies.com

double d = Convert.ToDouble(Console.ReadLine());

Console.Write("Enter boolean : ");


bool b = Convert.ToBoolean(Console.ReadLine());

Console.WriteLine("Integer value is : " + n);


Console.WriteLine("Double value is : " + d);
Console.WriteLine("Boolean value is : " + b);

}
}

Reading Character:
using System;
public class Program
{
public static void Main()
{
Console.Write("Enter character : ");
char ch = Console.ReadLine()[0];
Console.WriteLine("Character is : " + ch);
}
}

Reading Employee details:


using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Enter Emp details(id, name, gender, salary, married : ");
int id = Convert.ToInt32(Console.ReadLine());
String name = Console.ReadLine();
char gender = Console.ReadLine()[0];
double salary = Convert.ToDouble(Console.ReadLine());
bool married = Convert.ToBoolean(Console.ReadLine());

Console.WriteLine("Details : " + id + " , " + name + " , " + gender + " , " +
salary + " , " + married);
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 15


www.ameerpettechnologies.com

C# - Operators
Operator: Operator is a symbol that performs operation on operands.
Arithmetic operators:
• These operators perform all arithmetic operations.
• Operators are +, -, *, / , %
• Division(/) : returns quotient after division
• Mod(%) : returns remainder after division

public class Code {


public static void Main() {
int a=8, b=5 ;
Console.WriteLine(a + " + " + b + " = " + (a+b));
Console.WriteLine (a + " - " + b + " = " + (a-b));
Console.WriteLine(a + " * " + b + " = " + (a*b));
Console.WriteLine(a + " / " + b + " = " + (a/b));
Console.WriteLine(a + " % " + b + " = " + (a%b));
}
}

Operators Priority: We need to consider the priority of operators if the expression has more
than one operator. Arithmetic operators follow BODMAS rule.
Priority Operator
() First. If nested then inner most is first
*, / and % Next to (). If several, from left to right
+, - Next to *, / , %. If several, from left to right

Examples expressions with evaluations:


5+3-2 5*3%2 5+3*2 (5+3)*2
8-2 15%2 5+6 8*2
6 1 11 16

Practice codes on Arithmetic operators


Find the average of two numbers:
class Code
{
public static void Main() {
int num1= 5 , num2 = 3;
int avg = (num1+num2)/2;
Console.WriteLine("Average : " + avg);
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 16


www.ameerpettechnologies.com

Print Last Digit of given Number:


class Code
{
public static void Main()
{
Console.WriteLine("Enter a number : ");
int n = Convert.ToInt32(Console.ReadLine());
int d = n%10;
Console.WriteLine("Last digit of " + n + " is " + d);
} A
} M
E
Remove Last Digit of Given Number E
class Code R
{ P
public static void Main() E
{ T
Console.WriteLine("Enter a number : ");
T
int n = Convert.ToInt32(Console.ReadLine());
E
n = n/10;
C
Console.WriteLine("After remove last digit : " + n);
H
}
N
}
O
L
Calculate Total Salary of Employee:
O
class Code
G
{
I
public static void Main()
E
{ S
Console.WriteLine("Enter basic salary : ");
double basic = Convert.ToDouble(Console.ReadLine());
double hra = 0.25*basic;
double ta = 0.2*basic;
double da = 0.15*basic;
double total = basic + hra + ta + da ;
Console.WriteLine("Total Salary : " + total);
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 17


www.ameerpettechnologies.com

Relational operators: These operator return boolean value by validating the relation on data.
• Operators are >, < , >=, <=, ==, !=
class Code {
public static void Main() {
int a=5, b=3 ;
Console.WriteLine(a + ">" + b + "=" + (a>b));
Console.WriteLine(a + "<" + b + "=" + (a<b));
Console.WriteLine(a + "==" + b + "=" + (a==b));
Console.WriteLine(a + "!=" + b + "=" + (a!=b));
}
}

Conditional Operator:
• It is widely used to execute condition in true part or in false part.
• It is a simplified form of if-else control statement.

Checking if a number is even or odd:


int num = 5;
string result = (num % 2 == 0) ? "even" : "odd";
Console.WriteLine(result);

Finding the maximum of two numbers:


int num1 = 10;
int num2 = 5;
int max = (num1 > num2) ? num1 : num2;
Console.WriteLine(max);

Checking if a person is eligible to vote:


int age = 18;
string result = (age >= 18) ? "eligible to vote" : "not eligible to vote";
Console.WriteLine(result);

Calculating the absolute value of a number:


int num = -5;
int absNum = (num < 0) ? -num : num;
Console.WriteLine("The absolute value of {0} is {1}.", num, absNum);

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 18


www.ameerpettechnologies.com

Modify operators:

• These are also called Increment and Decrement operators.


• Modify operators are increase and decrease the value of variable by 1.
• Operators are ++, -- ;

Increase value of a variable by 1 in 3 ways:


x=10 -> x=x+1 -> x=11
x=10 -> x+=1 -> x=11
x=10 -> x++ -> x=11

Decrease value of a variable by 1 in the same way:


x=10 -> x=x-1 -> x=9
x=10 -> x-=1 -> x=9
x=10 -> x-- -> x=9

Logical Operators
• A logical operator is primarily used to evaluate multiple expressions.
• Logical operators return boolean value.
• Operators are && , || and !

When ‘A’ is When ‘B’ is A&&B is A||B is !A is !B is


T T T T F F
F T F T T F
T F F T F T
F F F F T T

class Logical {
public static void Main() {
Console.WriteLine("true && true : " + (true && true));
Console.WriteLine("true && false : " + (true && false));
Console.WriteLine("true || false : " + (true || false));
Console.WriteLine("false || false : " + (false || false));
}
}

class Logical {
public static void Main() {
Console.WriteLine("!true : " + (!true));
Console.WriteLine("!false : " + (!false));
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 19


www.ameerpettechnologies.com

Bitwise Operators:
• These operators are used to process the data at bit level.
• These can be applied only integers and characters.
• Operators are &, |, ^.
• These operators process the data according to truth table.

a b a&b a|b a^b ~a ~b


0 0 0 0 0 1 1
0 1 0 1 1 1 0
1 0 0 1 1 0 1
1 1 1 1 0 0 0

class Bitwise{
public static void Main() {
int a=10, b=8 , c, d, e;
c = a&b ;
d = a|b ;
e = a^b ;
Console.WriteLine(c+","+d+","+e);
}
}

Shift Operators:
• The bitwise shift operators move the bit values of a binary object.
• The left operand specifies the value to be shifted.
• The right operand specifies the number of positions that the bits in the value are to be
shifted.
• The bit shift operators take two arguments, and looks like:
▪ x << n
▪ x >> n

class Shift{
public static void Main() {
int a=8, b, c;
b = a>>2 ;
c = a<<2 ;
Console.WriteLine(a+","+b+","+c);
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 20


www.ameerpettechnologies.com

Conditions using Arithmetic, Relational and Logical operators

Condition to check the number is Positive or Negative:


Variables:
int a=?;

Condition:
a >= 0

Condition to check the number is equal to zero or not:


Variables:
int a=?;

Condition:
a == 0

Condition to check the 2 numbers equal or not:


Variables:
int a=?, b=?;

Condition:
a ==b

Condition to check First Num greater than Second Num or Not:


Variables:
int a=?, b=?;

Condition:
a>b

Square of First Number equals to Second Number or Not :


Variables:
int a=?, b=?;

Condition:
a*a == b

Condition to check sum of 2 numbers equal to 10 or not:


Variables:
int a=?, b=? ;

Condition:
a+b == 10 ;

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 21


www.ameerpettechnologies.com

Condition to check the number divisible by 3 or not:


Variables:
int n=?;

Condition:
n % 3 == 0

Condition to check the number is Even or not:


Variables:
int n=?;

Condition:
n % 2 == 0

Condition to check the last digit of Number is 0 or not:


Variables:
int n=?;

Condition:
n % 10 == 0

Condition to check the multiplication of 2 numbers not equals to 3rd number or not:
Variables:
int a=?, b=?, c=?;

Condition:
a * b != c

Condition to check average of 4 subjects marks greater than 60 or not:


Variables:
int m1=?, m2=?, m3=? , m4=? ;

Condition:
(m1 + m2+ m3+ m4)/4 >= 60

Condition to check the sum of First 2 numbers equals to last digit of 3rd num or not:
Variables:
int a=?, b=? , c=? ;

Condition:
a + b == c% 10

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 22


www.ameerpettechnologies.com

Condition to check the given quantity of fruits exactly in dozens or not:


Variables:
int quantity = ?;

Condition:
quantity%12 == 0

Condition to person is eligible for Vote or Not:


Variables:
int age=?;

Condition:
age >= 18

Condition to check First Num is greater than both Second & Third Nums or Not:
Variables:
int a=?, b=?, c=?;

Condition:
a > b && a > c

Condition to check the number divisible by both 3 and 5 or not:


Variables:
int n=?;

Condition:
n % 3 == 0 && n % 5 == 0

Condition to check the number is in between 30 and 50 or not:


Variables:
int n=?;

Condition:
n >= 30 && n <= 50

Condition to check the student passed in all 5 subjects or Not:


Variables:
int m1=?, m2=?, m3=?, m4=?, m5=?;

Condition:
m1>=35 && m2>=35 && m3>=35 && m4>=35 && m5>=35

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 23


www.ameerpettechnologies.com

Condition to check the character is Vowel or Not:


Variables:
int ch = ‘?’;

Condition:
ch == ‘a’ || ch == ‘e’ || ch== ‘i’ || ch==’o’ || ch==’u’

Condition to check the character is Upper case alphabet or not:


Variables:
int ch=’?’;

Condition:
ch >= ‘A’ && ch <= ‘Z’ A
M
E
Condition to check the character is Alphabet or not:
E
Variables:
R
int ch=’?’;
P
E
Condition:
T
(ch >= ‘A’ && ch <= ‘Z’) || (ch >= ‘a’ && ch <= ‘z’)
T
Condition to check the 3 numbers equal or not: E
Variables: C
int a=?, b=?, c=?; H
N
Condition: O
a == b && b == c L
O
Condition to check any 2 numbers equal or not among the 3 numbers: G
Variables: I
int a=? , b=? , c=?; E
S
Condition:
a==b || b==c || c=a

Condition to check the 3 numbers are unique or not:


Variables:
int a=? , b=? , c=?;

Condition:
a!=b && b!=c && c!=a

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 24


www.ameerpettechnologies.com

Control Statements
Sequential statements:
• Statement is a line of code.
• Sequential Statements execute one by one from top-down approach.

Control statements: Statements execute randomly and repeatedly based on conditions.

Conditional Loop Branching


If-block For loop Break
If-else block While loop Continue
If-else-if block Do-while loop Return
Nested if block Nested loops
Switch case

If block: execute a block of instructions only when condition is valid.


Syntax Flow Chart

if(condition)
{
Logic;
}

Example: Give 10% discount if the bill amount is > 5000


class Code
{
public static void Main()
{
double bill = 6000;
if(bill > 5000){
double discount = 0.1*bill ;
bill = bill - discount;
}
Console.WriteLine("Total bill amount is : " + bill);
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 25


www.ameerpettechnologies.com

if - else block: Else block can be used to execute an optional logic if the given condition has
failed.
Syntax Flow Chart

if (condition){
If – Stats;
}
else{
Else – Stats;
}

Program to check the number is even or odd


Even Number: The number which is divisible by 2
class Code
{
public static void Main() {
int n=5;
if(n%2==0)
Console.WriteLine("Even number");
else
Console.WriteLine("Not even number");
}
}

Program to Check Person can Vote or Not:


class Code
{
public static void Main() {

Console.WriteLine("Enter age : ");


int age = Convert.ToInt32(Console.ReadLine());
if(age>=18)
Console.WriteLine("Eligible for Vote");
else
Console.WriteLine("Wait " + (18-age) + " more years to vote");
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 26


www.ameerpettechnologies.com

If-else-if ladder:
• It is allowed to defined multiple if blocks sequentially.
• It executes only one block among the multiple blocks defined.
Syntax Flow Chart

if(condition1){
Statement1;
}
else if(condition2){
Statement2;
}
else if(condition3){
Statement3;
}
else{
Statement4;
}

Program to find Biggest of Three Numbers:


;
class Code
{
public static void Main()
{
Console.WriteLine("Enter a, b, c values : ");
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
int c = Convert.ToInt32(Console.ReadLine());
if(a>b && a>c)
Console.WriteLine("a is big");
else if(b>c)
Console.WriteLine("b is big");
else
Console.WriteLine("c is big");
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 27


www.ameerpettechnologies.com

Program to check the Character is Alphabet or Digit or Symbol


class Code
{
public static void Main()
{

Console.WriteLine("Enter character : ");


char ch = scan.nextLine().charAt(0);
if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
Console.WriteLine("Alphabet");
else if(ch>='0' && ch<='9')
Console.WriteLine("Digit");
else
Console.WriteLine("Special Symbol");
}
}

Program to check the input year is Leap or Not:


Leap Year rules:
• 400 multiples are leap years : 400, 800, 1200, 1600….
• 4 multiples are leap years: 4, 8, 12, … 92, 96…
• 100 multiples are not leap years: 100, 200, 300, 500, 600…

class Code
{
public static void Main()
{

Console.WriteLine("Enter year : ");


int n = Convert.ToInt32(Console.ReadLine());
if((n%400==0))
Console.WriteLine("Leap year");
else if(n%4==0 && n%100!=0)
Console.WriteLine("Leap Year");
else
Console.WriteLine("Not leap year");
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 28


www.ameerpettechnologies.com

Nested if block: Defining a block inside another block. Inner if block condition evaluates only if
the outer condition is valid. It is not recommended to write many levels to avoid complexity.
Syntax Flow Chart
if (condition){
if (condition){
If - If….
}
else {
If - Else….
}
}
else {
if (condition){
Else - If….
}
else {
Else - Else….
}
}

Give the student grade only if the student passed in all subjects:
class Code
{
public static void Main() {
int m1=45, m2=67, m3=44;
if(m1>=40 && m2>=40 && m3>=40){
int total = m1+m2+m3;
int avg = total/3;
if(avg>=60)
Console.WriteLine("Grade-A");
else if(avg>=50)
Console.WriteLine("Grade-B");
else
Console.WriteLine("Grade-C");
}
else
{
Console.WriteLine("Student failed");
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 29


www.ameerpettechnologies.com

Introduction to Loops

Loop: A Block of instructions execute repeatedly as long the condition is valid.

A
M
E
E
R
P
Note: Block executes only once whereas Loop executes until condition become False E
T
Java Supports 3 types of Loops:
T
1. For Loop
E
2. While Loop C
3. Do-While Loop H
N
For Loop: We use for loop only when we know the number of repetitions. For example, O
L
• Print 1 to 10 numbers
O
• Print Array elements G
• Print Multiplication table I
• Print String character by character in reverse order E
S
While loop: We use while loop when we don’t know the number of repetitions.
• Display contents of File
• Display records of Database table

Do while Loop: Execute a block at least once and repeat based on the condition.
• ATM transaction: When we swipe the ATM card, it starts the first transaction. Once the
first transaction has been completed, it asks the customer to continue with another
transaction and quit.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 30


www.ameerpettechnologies.com

For Loop
for loop: Execute a block of instructions repeatedly as long as the condition is valid. We
use for loop only when we know the number of iterations to do.

Syntax Flow Chart

for(init ; condition ; modify)


{
statements;
}

for(start ; stop ; step)


{
statements;
}

Program to Print 1 to 10 Numbers


class Code {
public static void Main() {
for (int i=1 ; i<=10 ; i++){
Console.WriteLine("i val : " + i);
}
}
}

Program to Print 10 to 1 numbers


class Code{
public static void Main() {
for (int i=10 ; i>=1 ; i--){
Console.WriteLine("i val : " + i);
}
}
}

Program to display A-Z alphabets


class Code {
public static void Main() {
for (char ch='A' ; ch<='Z' ; ch++){
Console.Write(ch + " ");
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 31


www.ameerpettechnologies.com

While Loop
While loop: Execute a block of instructions repeatedly until the condition is false. We
use while loop only when don’t know the number of iterations to do.

Syntax Flow Chart

while(condition)
{
statements;
}

Program to Count the digits in given number


class Code
{
public static void Main()
{

Console.Write("Enter Num : ");


int n = Convert.ToInt32(Console.ReadLine());
int count=0;
while(n!=0)
{
n=n/10;
count++;
}
Console.WriteLine("Digits count : " + count);
}
}

Display sum of the digits in the given number


class Code
{
public static void Main()
{

Console.Write("Enter Num : ");


int n = Convert.ToInt32(Console.ReadLine());
int sum=0;

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 32


www.ameerpettechnologies.com

while(n!=0)
{
sum = sum + n%10;
n=n/10;
}
Console.WriteLine("Sum of digits : " + sum);
}
}

Check the given 3 digit number is Armstrong Number or not :


Sum of cubes of individual digits equals to the same number
Example: 153 -> 1^3 + 5^3 + 3^3 = 153

class Code
{
public static void Main()
{
Console.Write("Enter Num : ");
int n = Convert.ToInt32(Console.ReadLine());
int temp, sum=0, r;
temp=n;
while(n>0)
{
r = n%10;
sum = sum + r*r*r;
n = n/10;
}
if(temp==sum)
Console.WriteLine("ArmStrong Number");
else
Console.WriteLine("Not an ArmStrong Number");
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 33


www.ameerpettechnologies.com

Break and Continue

break: A branching statement that terminates the execution flow of a Loop or Switch
case.
class Code {
public static void Main() {
for (int i=1 ; i<=10 ; i++){
if(i==5){
break;
}
Console.Write(i + " ");
}
}
}
Output: 1 2 3 4

Break statement terminates the flow of infinite loop also:


class Code {
public static void Main() {
while(true){
Console.Write("Loop");
break;
}
}
}
Output: Loop prints infinite times

Continue: A branching statement that terminates the current iteration of loop execution.
class Code {
public static void Main() {
for (int i=1 ; i<=10 ; i++){
if(i==5){
continue;
}
Console.Write(i + " ");
}
}
}
Output: 1 2 3 4 5 6 7 8 9 10

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 34


www.ameerpettechnologies.com

Switch case
Switch: It is a conditional statement that executes specific set of statements(case) based on
given choice. Default case executes if the user entered invalid choice. Case should terminate
with break statement.

Syntax FlowChart

switch(choice)
{
case 1 : Statements ;
break
case 2 : Statements ;
break
......

case n : Statements ;
break
default: Statements ;
}

class Code
{
public static void Main() {
Console.Write("Enter character(r, g, b) : ");
char ch = sc.next().charAt(0);
switch(ch){
case 'r' : Console.WriteLine("Red");
break;
case 'g' : Console.WriteLine("Green");
break;
case 'b' : Console.WriteLine("Blue");
break;
default : Console.WriteLine("Weird");
}
}
}
Output: Enter character(r, g, b): g
Green

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 35


www.ameerpettechnologies.com

Do-While Loop
do-while: Executes a block at least once and continue iteration until condition is false.

Syntax Flow Chart

do
{
statements;
} while(condition);

Check Even numbers until user exits:


class Code
{
public static void Main() {

char res='n';
do{
Console.Write("Enter num : ");
int n = Convert.ToInt32(Console.ReadLine());
if(n%2==0)
Console.WriteLine(n + " is even");
else
Console.WriteLine(n + " is not even");

Console.Write("Do you want to check another num (y/n) : ");


res = sc.next().charAt(0);
}while (res == 'y');
}
}
Output: Enter num : 5
5 is not even
Do you want to check another num (y/n) : y
Enter num : 6
6 is even
Do you want to check another num (y/n) : n

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 36


www.ameerpettechnologies.com

C# – Object Oriented Programming

Application:
• Programming Languages and Technologies are used to develop applications.
• Application is a collection of Programs.
• We need to design and understand a single program before developing an application.

Program Elements: Program is a set of instructions. Every Program consists,


1. Identity
2. Variables
3. Methods

1. Identity:
o Identity of a program is unique. A
o Programs, Classes, Variables and Methods having identities M
o Identities are used to access these members. E
E
2. Variable: R
o Variable is an identity given to memory location. P
or E
o Named Memory Location T
o Variables are used to store information of program(class/object)
T
E
Syntax Examples
C
H
datatype identity = value; String name = “amar”;
N
int age = 23;
O
double salary = 35000.00; L
bool married = false; O
G
I
3. Method: E
• Method is a block of instructions with an identity S
• Method performs operations on data(variables)
• Method takes input data, perform operations on data and returns results.

Syntax Example
returntype identity(arguments) int add(int a, int b)
{ {
body; int c = a+b;
} return c;
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 37


www.ameerpettechnologies.com

Introduction to Object oriented programming:


• C# is Object Oriented Programming language.
• OOPs is the concept of defining objects and establish communication between them.
• The Main principles of Object-Oriented Programming are,
1. Encapsulation
2. Inheritance
3. Abstraction
4. Polymorphism
Note: We implement Object-Oriented functionality using Classes and Objects

Class: Class contains variables and methods. C# application is a collection of classes


Syntax Example
class Account{
long num;
class ClassName double balance;
{ void withdraw(){
Variables ; logic;
& }
Methods ; void deposit(){
} logic;
}
}
Object: Object is an instance of class. Instancevariables of class get memory inside the Object.

Syntax: ClassName reference = new ClassName();


Example: Account acc = new Account();

Note: Class is a Model from which we can define multiple objects of same type

Encapsulation:
• The concept of protecting the data with in the class itself.
• Implementation rules: (POJO rules)
o Class is Public (to make visible to other classes).
o Variables are Private (other objects cannot access the data directly).
o Methods are public (to send and receive the data).

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 38


www.ameerpettechnologies.com

Inheritance: Defining a new class by re-using the members of other class. We can implement
inheritance using “extends” keyword.
• Terminology:
o Parent/Super class: The class from which members are re-used.
o Child/Sub class: The class which is using the members

Abstraction:
• Abstraction is a concept of hiding implementations and shows functionality.
• Abstraction describes "What an object can do instead how it does it?".

Polymorphism:
• Polymorphism is the concept where object behaves differently in different situations.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 39


www.ameerpettechnologies.com

Variables in C#

Variables:
• Variable stores information of class(object).
• Variables classified into 4 types to store different types of data.

1. Static Variables: Store common information of all Objects. Access static variables using
class-name.
2. Instance Variables: Store specific information of Object. Access instance variables using
object-reference.
3. Method Parameters: Takes input in a Method. Access Method parameters directly and
only inside the method.
4. Local Variables: Store processed information inside the Method. Access local variables
directly and only inside the method.

Accessing different types of variables in C#:

Static Variables: Access using Class-Name.


Instance Variables: Access using Object-Name.
Local Variables: Direct access & only with in the method.
Method Parameters: Direct access & only with in the method.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 40


www.ameerpettechnologies.com

Methods
Method:
• A block of instructions having identity.
• Methods takes input(parameters), process input and return output.
• Methods are used to perform operations on data
Syntax Example
returntype identity(arguments){ int add(int a, int b){
statements; int c=a+b;
} return c;
}

Classification of Methods: Based on taking input and returning output, methods are classified
into 4 types.

Method Definition: Method definition consists logic to perform the task. It is a block.
Method Call: Method Call is used to invoke the method logic. It is a single statement.

Static Method: Defining a method using static keyword. We can access static methods using
class-name.
static void display()
{
logic;
}

Instance Method: Defining a method without static keyword. We can access instance methods
using object-reference.
void display()
{
logic;
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 41


www.ameerpettechnologies.com

No arguments and No return values method:


public class Program{
public static void Main(){
Program.fun();
}
static void fun(){
Console.WriteLine("fun");
}
}

With arguments and No return values:


public class Program{
public static void Main(){
Program.isEven(13);
}
static void isEven(int n){
if(n%2==0)
Console.WriteLine("Even");
else
Console.WriteLine("Odd");
}
}

With arguments with return values:


public class Program{
public static void Main(){
int sum = Program.add(10,20);
Console.WriteLine("Sum is = " + sum);
}
static int add(int a, int b){
return a+b;
}
}

No arguments and with return values:


public class Program{
public static void Main(){
double PI = Program.getPI();
Console.WriteLine("PI value is = " + PI);
}
static double getPI(){
double pi = 3.142;
return pi;
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 42


www.ameerpettechnologies.com

Static Variables

Static Variable:
• Defining a variable inside the class and outside to methods.
• Static variable must define with static keyword.
• Static Variable access using Class-Name.

class Bank
{
static String bankName = "AXIS";
}
Note: We always process the data (perform operations on variables) using methods.

Getter and Setter Methods:


• set() method is used to set the value to variable.
• get() method is used to get the value of variable.
• Static variables : process using static set() and get() methods
• Instance variables : process using instance set() and get() methods
public class Program
{
static int a;
static void setA(int a){
Program.a = a;
}
static int getA(){
return Program.a;
}
public static void Main()
{
Program.setA(10);
Console.WriteLine(Program.getA());
}
}

Static variables automatically initialized with default values based on datatypes:

Datatype Default Value


int 0
double 0
char Blank
bool false
String Null (blank)

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 43


www.ameerpettechnologies.com

using System;
class Program
{
static int num;
static bool isTrue;
static double dblNum;
static string str;
static void Main(string[] args)
{
Console.WriteLine("Default values of static variables:");
Console.WriteLine("num: {0}", num);
Console.WriteLine("isTrue: {0}", isTrue); A
Console.WriteLine("dblNum: {0}", dblNum); M
Console.WriteLine("str: {0}", str); E
} E
} R
P
It is recommended to define get() and set() method to each variable in the class: E
public class Program T
{
T
public static void Main()
E
{
C
First.setA(10);
H
First.setB(20);
N
Console.WriteLine("A val : " + First.getA());
O
Console.WriteLine("B val : " + First.getB()); L
} O
} G
class First{ I
static int a, b, c; E
public static void setA(int a){ S
First.a = a;
}
public static void setB(int b){
First.b = b;
}
public static int getA(){
return First.a;
}
public static int getB(){
return First.b;
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 44


www.ameerpettechnologies.com

Instance Members in C#

Instance Members:
• Instance members also called non-static members.
• Instance members related to Object.
• We invoke instance members using Object-address

Object Creation of a Class in C#:


Syntax:
ClassName ref = new ClassName();
Example:
Employee emp = new Employee();

Constructor:
• Defining a method with Class-Name.
• Constructor Not allowed return-type.

class Employee
{
public Employee()
{
Console.WriteLine("Object created");
}
}

We must invoke the constructor in Object creation process:


public class Program
{
public static void Main()
{
Employee emp = new Employee();
}
}
class Employee
{
public Employee()
{
Console.WriteLine("Object created");
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 45


www.ameerpettechnologies.com

Instance Method:
• Defining a method without static keyword.
• We must invoke the method using object-reference.

No arguments and No return values method:


public class Program
{
public static void Main(){
Program obj = new Program();
obj.fun();
}
void fun(){
Console.WriteLine("fun");
}
}

With arguments and No return values method:


public class Program
{
public static void Main(){
Program obj = new Program();
obj.isEven(12);
}
void isEven(int n){
if(n%2==0)
Console.WriteLine("even");
else
Console.WriteLine("odd");
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 46


www.ameerpettechnologies.com

With arguments and with return values method:


public class Program{
public static void Main(){
Program obj = new Program();
int sum = obj.add(10, 20);
Console.WriteLine("Sum is = " + sum);
}
int add(int a, int b){
int c = a+b;
return c;
}
}

No arguments and with return values:


public class Program
{
public static void Main(){
Program obj = new Program();
double PI = obj.getPI();
Console.WriteLine("PI value is = " + PI);
}
double getPI(){
double PI = 3.142;
return PI;
}
}

Instance Variables:
• Defining a variable inside the class and outside to methods.
• Instance variables get memory inside every object and initializes with default values.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 47


www.ameerpettechnologies.com

this:
• It is a keyword and pre-defined instance variable in C#.
• It is also called Default Object Reference Variable.
• “this-variable” holds object address.
o this = object_address;
• It is used to access object inside the instance methods and constructor.

Parameterized constructor:
• Constructor with parameters is called Parameterized constructor.
• We invoke the constructor in every object creation process.
• Parameterized constructor is used to set initial values to instance variables in Object
creation process.

Note: We invoke the constructor with parameter values in object creation as follows
public class Program{
int a;
Program(int a){
this.a = a;
}
public static void Main(){
Program p = new Program(10); //pass parameter while invoking constructor
}
}

Program to create two Employee objects with initial values:


public class Employee{
int id;
String name;
Employee(int id, String name){
this.id = id;
this.name = name;
}
void details(){
Console.WriteLine(this.id + ", " + this.name);
}
public static void Main() {
Employee e1 = new Employee(101, "Amar");
Employee e2 = new Employee(102, "Annie");
e1.details();
e2.details();
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 48


www.ameerpettechnologies.com

Accessing variables using set() and get() methods:


using System;
class Employee
{
private int id;
private string name;
public void setId(int id)
{
this.id=id; A
} M
public void setName(string name) E
{ E
this.name = name; R
} P
public int getId() E
{ T
return this.id;
T
}
E
public string getName()
C
{
H
return this.name;
N
}
O
}
L
O
public class Access G
{ I
public static void Main() E
{ S
Employee e = new Employee();
e.setId(101);
e.setName("Amar");
Console.WriteLine(e.getId());
Console.WriteLine(e.getName());
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 49


www.ameerpettechnologies.com

Access Modifiers

Access Modifiers: Access modifiers are used to set permissions to access the Class and its
members (variables, methods & constructors).

Public: The public keyword allows its members to be visible from anywhere inside the project.
Private: The private members can only be accessed by the member within the same class.
Protected: Protected accessibility allows the member to be accessed from within the class and
from another class that inherits this class.
Internal: Internal provides accessibility from within the project. Another similar internal
accessibility is protected internal. This allows the same as the internal and the only difference is
that a child class can inherit this class and reach its members even from another project.

Private access modifier:


class MyClass
{
private int num; // private variable
private void DisplayNum() // private method
{
Console.WriteLine("num = " + num);
}
public void SetNum(int n) // public method
{
num = n;
}
public void ShowNum() // public method
{
DisplayNum();
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 50


www.ameerpettechnologies.com

class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
obj.SetNum(10);
obj.ShowNum(); // Output: num = 10
}
}

Protected access modifier:


class MyClass
{
protected int num; // protected variable
protected void DisplayNum() // protected method
{
Console.WriteLine("num = " + num);
}
}
class MyDerivedClass : MyClass
{
public void SetNum(int n)
{
num = n; // accessing protected variable
}

public void ShowNum()


{
DisplayNum(); // accessing protected method
}
}

class Program
{
static void Main(string[] args)
{
MyDerivedClass obj = new MyDerivedClass();
obj.SetNum(10);
obj.ShowNum(); // Output: num = 10
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 51


www.ameerpettechnologies.com

Encapsulation:
• The concept of protecting the data with in the class itself.
• We implement Encapsulation through POCO rules
• POCO – Plain Old CLR Object

Employee.cs:
public class Employee {
private int num;
private string name;
private double salary;
public void setNum(int num){
this.num = num;
}
public int getNum(){
return this.num;
}
public void setName(string name){
this.name = name;
}
public string getName(){
return this.name;
}
public void setSalary(double salary){
this.salary = salary;
}
public double getSalary(){
return this.salary;
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 52


www.ameerpettechnologies.com

AccessEmployee.cs:
public class AccessEmployee{
public static void Main() {
Employee e = new Employee();
e.setNum(101);
e.setName("Amar");
e.setSalary(35000);
Console.WriteLine("Emp Num : "+e.getNum());
Console.WriteLine("Emp Name : "+ e.getName());
Console.WriteLine("Emp Salary : "+e.getSalary());
}
}

We can simple define Employee class and Accessing class as follows:


using System;
public class Employee
{
private int id;
private string name;
private decimal salary;
public int Id
{
get { return id; }
set { id = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
}
public class Access
{
public static void Main()
{
Employee obj = new Employee();
obj.Id = 101;
obj.Name = "Amar";
Console.WriteLine("Id is : " + obj.Id);
Console.WriteLine("Name is : " + obj.Name);
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 53


www.ameerpettechnologies.com

Constructor Chaining:
• Invoking constructor from another constructor is called Chaining.
• this() method is used to invoke constructor.

using System;
public class Test
{
public Test() : this(10)
{
Console.WriteLine("Zero args");
}
public Test(int x) : this(10, 20)
{
Console.WriteLine("Args");
}
public Test(int x, int y)
{
Console.WriteLine("Two args");
}
}
public class Access
{
public static void Main()
{
Test obj = new Test();
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 54


www.ameerpettechnologies.com

Inheritance
Inheritance:
• Defining a new class by re-using the members of other class.
• We can implement inheritance using “extends” keyword.
• Terminology:
o Parent/Super class: The class from which members are re-used.
o Child/Sub class: The class which is using the members

Types of Inheritance:
1. Single Inheritance
2. Multi-Level Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

Note: We can achieve above relations through classes


class A{
…..
}
class B : A{
…..
}

class A{
....
}
class B : A{
....
}
class C : B{
....
}
class A{
....
}
class B : A{
....
}
class C : A{
....
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 55


www.ameerpettechnologies.com

The two other inheritance types are:


1. Multiple Inheritance
2. Hybrid Inheritance

We cannot achieve multiple inheritance through Classes:


class A{
....
}
class B{
....
}
class C : A, B{
....
}

We can achieve multiple inheritance in C# through interfaces:


• A class can implements more than one interface
• An interface extends more than one interface is called Multiple Inheritance

Interface A{
}
Interface B{
}
Class C : A, B{
}

Interface A{
}
Interface B{
}
Interface C : A, B{
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 56


www.ameerpettechnologies.com

Note: We always instantiate (create object) of Child in Inheritance

A
M
Single Inheritance: By instantiating child class, we can access both Parent & Child E
functionality. E
using System; R
public class Employee { P
public void doWork(){ E
Console.WriteLine("Employee do work"); T
}
T
}
E
public class Manager : Employee {
C
public void monitorWork(){ H
Console.WriteLine("Manage do work as well as monitor others work"); N
} O
} L
public class Company { O
public static void Main() { G
Manager m = new Manager(); I
m.doWork(); E
m.monitorWork(); S
}
}

Accessing Protected functionality of Parent from Child:


using System;
class Employee {
protected void doWork(){
Console.WriteLine("Employee do work");
}
}
class Manager : Employee {
public void monitorWork() {
doWork();
Console.WriteLine("Manage do work as well as monitor others work");

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 57


www.ameerpettechnologies.com

}
}
public class Company {
public static void Main() {
Manager m = new Manager();
m.monitorWork();
}
}

In Object creation, Parent object creates first to inherit properties into Child.
We can check this creation process by defining constructors in Parent and Child.

using System;
class Parent{
public Parent(){
Console.WriteLine("Parent instantiated");
}
}
class Child : Parent{
public Child(){
Console.WriteLine("Child instantiated");
}
}
public class Inherit {
public static void Main(){
new Child();
}
}

this this()
A reference variable used to invoke instance It is used to invoke the constructor of same
members. class.
It must be used inside instance method or It must be used inside the constructor.
instance block or constructor.

base base()
A reference variable used to invoke instance It is used to invoke the constructor of same
members of Parent class from Child class. class.
It must be used inside instance method or It must be used inside Child class constructor.
instance block or constructor of Child class.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 58


www.ameerpettechnologies.com

Method overriding:
• If derived class defines same method as defined in its base class, it is known as method
overriding in C#.
• It is used to achieve runtime polymorphism.
• It enables you to provide specific implementation of the method which is already
provided by its base class.
• To perform method overriding in C#, you need to use virtual keyword with base class
method and override keyword with derived class method

using System;
class Parent{
public virtual void fun(){
Console.WriteLine("Parent functionality");
}
}
class Child : Parent{
public override void fun(){
Console.WriteLine("Child functionality");
}
}
public class Inherit {
public static void Main(){
Parent p = new Child();
p.fun();
}
}

Accessing Parent class overridden method using “base”:


using System;
class Parent{
public virtual void fun(){
Console.WriteLine("Parent functionality");
}
}
class Child : Parent{
public override void fun(){
Console.WriteLine("Child functionality");
}
public void access(){
this.fun();
base.fun();
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 59


www.ameerpettechnologies.com

public class Inherit {


public static void Main(){
Child c = new Child();
c.access();
}
}

base():
• In inheritance, we always create Object to Child class.
• In Child object creation process, we initialize instance variables of by invoking Parent
constructor from Child constructor using base().

using System;
class Parent{
public int a, b;
public Parent(int a, int b)
{
this.a = a;
this.b = b;
}
}
class Child : Parent{
public int c, d;
public Child(int a, int b, int c, int d) : base(a, b)
{
this.c = c;
this.d = d;
}
public void details()
{
Console.WriteLine("Parent a : " + base.a);
Console.WriteLine("Parent b : " + base.b);
Console.WriteLine("Child c : " + this.c);
Console.WriteLine("Child d : " + this.d);
}
}
public class Inherit {
public static void Main(){
Child c = new Child(10, 20, 30, 40);
c.details();
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 60


www.ameerpettechnologies.com

Polymorphism:
• Polymorphism is the concept where object behaves differently in different situations.

Polymorphism is of two types:


1. Compile time polymorphism
2. Runtime polymorphism

Compile time polymorphism:


• It is method overloading technique.
• Defining multiple methods with same name and different signature(parameters).
• Parameters can be either different length or different type.
• Overloading belongs to single class(object).

using System;
class Calculator {
public void add(int x, int y) {
int sum = x+y;
Console.WriteLine("Sum of 2 numbers is : " + sum);
}
public void add(int x, int y, int z)
{
int sum = x+y+z;
Console.WriteLine("Sum of 3 numbers is : " + sum);
}
}
public class Overload{
public static void Main()
{
Calculator calc = new Calculator();
calc.add(10, 20);
calc.add(10, 20, 30);
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 61


www.ameerpettechnologies.com

WriteLine() method is pre-defined and overloaded. Hence it can print any type of data:
using System;
public class Overload
{
public static void Main()
{
Console.WriteLine(10);
Console.WriteLine(23.45);
Console.WriteLine("C#");
}
}

Runtime polymorphism:
• Runtime Polymorphism is a Method overriding technique.
• Defining a method in the Child class with the same name and same signature of its
Parent class.
• We can implement Method overriding only in Parent-Child (Is-A) relation.

Child object shows the functionality(behavior) of Parent and Child is called Polymorphism

using System;
class Parent{
public virtual void behave(){
Console.WriteLine("Parent behavior");
}
}
class Child : Parent{
public override void behave(){
Console.WriteLine("Child behavior");
}
public void behavior(){
base.behave();
this.behave();
}
}
public class Overrriding{
public static void Main(){
Child child = new Child();
child.behavior();
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 62


www.ameerpettechnologies.com

Object Up-casting:
• We can store the address of Child class into Parent type reference variable.

Using parent address reference variable, we can access the functionality of Child class.
using System;
class Parent {
public virtual void fun(){
Console.WriteLine("Parent's functionality");
}
}
class Child : Parent{
public override void fun(){
Console.WriteLine("Updated in Child");
}
}
public class Upcast {
public static void Main() {
Parent addr = new Child();
addr.fun();
}
}

Why it is calling Child functionality in the above application?


• Hostel address = new Student();
o address.post(); -> The Post reaches student
• Owner address = new Tenant();
o address.post(); -> The Pose reaches tenant

Down casting: The concept of collecting Child object address back to Child type reference
variable from Parent type.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 63


www.ameerpettechnologies.com

Sealed Classes
sealed:
• sealed is a keyword/modifier.
• A member become constant if we define it is sealed hence cannot be modified.
• We can apply sealed modifier to Class or Method or Variable.

If Class is sealed, cannot be inherited:


sealed class A{
}
class B : A{
}

If Method is final, cannot be overridden:


using System;
class X {
protected virtual void F1(){
}
protected virtual void F2(){
}
}
class Y : X {
sealed protected override void F1(){
}
protected override void F2() {
}
}
class Z : Y {
protected override void F() { // Error:
}
}

If the variable is final become constant and cannot be modified:


using System; using System;
public class Test{ public class Test{
static double PI = 3.14; sealed static double PI = 3.14;
public static void Main() { public static void Main(){
Console.WriteLine("PI val = " + PI); Console.WriteLine("PI val = " + PI);
PI = 3.142; PI = 3.142; // Error:
Console.WriteLine("PI val = " + PI); Console.WriteLine("PI val = " + PI);
} }
} }

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 64


www.ameerpettechnologies.com

Abstraction
Abstraction:
• Abstraction is a concept of hiding implementations and shows required functionality.
• Abstraction describes "What an object can do instead how it does it?".

A
M
Abstract Class: Define a class with abstract keyword. Abstract class consists concrete methods E
and abstract methods. E
R
Concrete Method: A Method with body P
Abstract Method: A Method without body E
T
Class Abstract Class
Class allows only Concrete methods Abstract Class contains Concrete and Abstract T
methods E
class A{ abstract class A C
public void m1(){ { H
logic; public void m1(){ N
} logic; O
public void m2(){ } L
logic; public abstract void m2(); O
} } G
} I
E
Note: We cannot instantiate (create object) to abstract class because it has undefined methods. S

abstract class A{
public abstract void m1();
public void m2(){
}
}
public class Access{
public static void Main(){
A obj = new A(); // Error :
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 65


www.ameerpettechnologies.com

Extending Abstract class:


• Every abstract class need extension (child).
• Child override the abstract methods of Abstract class.
• Through Child object, we can access the functionality of Parent (Abstract).

using System;
public abstract class Parent
{
public abstract void m1();
public void m2()
{
Console.WriteLine("Parent concrete method");
}
}
public class Child : Parent
{
public override void m1()
{
Console.WriteLine("Parent abstract method");
}
}
public class Access
{
public static void Main()
{
Child obj = new Child();
obj.m1();
obj.m2();
}
}

Initializing abstract class instance variables:


• Abstract class can have instance variables.
• Using base(), we initialize Abstract class instance variables in Child object creation
process.

using System;
abstract class Parent
{

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 66


www.ameerpettechnologies.com

public int a, b;
public Parent(int a, int b)
{
this.a = a;
this.b = b;
}
public abstract void details();
}
class Child : Parent
{
public int c, d;
public Child(int a, int b, int c, int d) : base(a, b)
{
this.c = c;
this.d = d;
}
public override void details()
{
Console.WriteLine("Parent a : " + base.a);
Console.WriteLine("Parent b : " + base.b);
Console.WriteLine("Child c : " + this.c);
Console.WriteLine("Child d : " + this.d);
}
}
public class Abstraction
{
public static void Main()
{
Child c = new Child(10, 20, 30, 40);
c.details();
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 67


www.ameerpettechnologies.com

Interfaces
Interface:
• Interface allow to define only abstract methods.
• Interface methods are ‘public abstract’ by default.

interface Sample {
void m1();
void m2();
}

Implementing an interface:
• Any class can implement the interface by overriding the methods of interface.
• We override the methods of interface using public modifier.

using System;
interface First {
void m1();
void m2();
}

class Second : First


{
public void m1(){
Console.WriteLine("m1....");
}
public void m2(){
Console.WriteLine("m2....");
}
}
public class Implement
{
public static void Main(){
First obj = new Second();
obj.m1();
obj.m2();
}
}

Upcasting: object reference of implemented class storing into Interface type variable

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 68


www.ameerpettechnologies.com

Multiple Inheritance in C#:


• A class can extends only class
• A class can extends class and implements any number of interfaces
• An interface can extend any number of interfaces called ‘Multiple Inheritance’

class A{
}
class B{
}
class C : A, B{
}

class A{
}
interface B{
}
class C : A, B{
}

interface A{
}
interface B{
}
class C : A, B{
}

• C# does not support multiple inheritance using classes.


• However, multiple inheritance can be achieved using interfaces.
• Here's an example program that demonstrates multiple inheritance using interfaces in
C#:

using System;
interface A
{
void m1();
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 69


www.ameerpettechnologies.com

interface B
{
void m2();
}
class C : A, B
{
public void m1()
{
Console.WriteLine("m1...");
}
public void m2()
{
Console.WriteLine("m2...");
}
}
public class Multiple
{
public static void Main()
{
C obj = new C();
obj.m1();
obj.m2();
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 70


www.ameerpettechnologies.com

Objects - Relations

Three most common relationships among classes in Java:

Use-A relation: When we create an object of a class inside a method of another class, this
relationship is called dependence relationship in Java, or simply Uses-A relationship.

BankEmployee use Customer Account objects to perform their transactions

Is-A relation: Is-A relationship defines the relationship between two classes in which one class
extends another class.

Every Employee is a Person


Every Manager is an Employee

Has-A relation: When an object of one class is created as data member inside another class, it
is called association relationship in java or simply Has-A relationship.

Every Person object Has Address object

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 71


www.ameerpettechnologies.com

There are two types of Has-A relationship that are as follows:

Aggregation : Establish a weak Has-A relation between objects.


For example, Library Has Students.
If we destroy Library, Still student objects alive.

Composition : Establish a Strong Has-A relation between objects.


For example, Person Has Aadhar.
If the Person died, Aadhar will not work there after.

Association:
• Association is a relationship between two objects.
• It’s denoted by “has-a” relationship.
• In this relationship all objects have their own lifecycle and there is no owner.
• In Association, both object can create and delete independently.

One to One: One Customer Has One ID


One Menu Item has One ID

One to Many: One Customer can have number of Menu orders

Many to One: One Menu Item can be ordered by any number of Customers

Many to Many: N number of customers can order N menu items

Program implementation for following Has-A relation :

class Author
{
String authorName;
int age;
String place;

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 72


www.ameerpettechnologies.com

Author(String name, int age, String place)


{
this.authorName = name;
this.age = age;
this.place = place;
}
}

class Book
{ A
String name; M
int price; E
Author auther; E
Book(String n, int p, Author auther) R
{ P
this.name = n; E
this.price = p; T
this.auther = auther;
T
}
E
void bookDetails()
C
{
H
Console.WriteLine("Book Name: " + this.name);
N
Console.WriteLine("Book Price: " + this.price); O
} L
void authorDetails() O
{ G
Console.WriteLine("Auther Name: " + this.auther.authorName); I
Console.WriteLine("Auther Age: " + this.auther.age); E
Console.WriteLine("Auther place: " + this.auther.place); S
}
public static void Main()
{
Author auther = new Author("Srinivas", 33, "INDIA");
Book obj = new Book("Java-OOPS", 200, auther);
obj.bookDetails();
obj.authorDetails();
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 73


www.ameerpettechnologies.com

Arrays in C#
Array:
• Array is a collection of similar data elements.
• Arrays are objects in Java.
• Arrays are static(fixed in size).

Syntax :
datatype identity[ ] = new datatype[size];

Example :
int arr[ ] = new int[5];

Declaration of array: The following code describes how to declare array variable in java. We
must allocate the memory to this variable before storing data elements.
class Code {
public static void Main() {
int arr[];
}
}

Allocate memory to array:


class Code {
public static void Main() {
int arr1[] ; // Declaration
arr1 = new int[5]; // memory allocation
int arr2[ ] = new int[5];
}
}

length: ‘length’ is an instance variable of Array class. It returns the length of array.
class Code {
public static void Main() {
int arr[ ] = new int[5];
int len = arr.length ;
Console.WriteLine("Length is : " + len);
}
}

Direct Initialization of Array:


• We can initialize the array directly using assignment operator.
• We process elements using index.
• Index starts with 0 to length-1.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 74


www.ameerpettechnologies.com

class Code {
public static void Main() {
int arr[ ] = {10,20,30,40,50};
Console.WriteLine("Array elements are : ");
for (int i=0 ; i<arr.length ; i++){
Console.WriteLine(arr[i]);
}
}
}

Array stores only homogenous elements. Violation result compilation Error


class Code {
public static void Main() {
int arr[ ] = new int[5];
arr[0] = 10 ;
arr[1] = 20 ;
arr[2] = 2.34 ; // Error :
}
}

System.IndexOutOfRangeException: Accessing the location which is not in the index between 0


to Length-1 results Exception
class Code {
public static void Main() {
int arr[ ] = new int[5];
arr[0] = 10 ;
arr[1] = 20 ;
arr[6] = 30 ; // Exception : Array memory allocate at runtime.
}
}

Read the size and construct Array Object:


;
class Code {
public static void Main() {

Console.Write("Enter array size : ");


int n = Convert.ToInt32(Console.ReadLine());
int arr[ ] = new int[n];
Console.WriteLine("Length is : " + arr.length);
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 75


www.ameerpettechnologies.com

Program read the Size and elements of array – Print their Sum:
class Code {
public static void Main() {
Console.Write("Enter array size : ");
int n = Convert.ToInt32(Console.ReadLine());
int arr[ ] = new int[n];
Console.WriteLine("Enter " + n + " values : ");
for (int i=0 ; i<n ; i++){
arr[i] = Convert.ToInt32(Console.ReadLine());
}
int sum=0;
for (int i=0 ; i<n ; i++){
sum = sum + arr[i];
}
Console.WriteLine("Sum of elements : " + sum);
}
}

for-each loop (enhanced for loop) :


• By which we can iterate Arrays and Collections easily.
• No need to specify the bounds (indexes) in for-each loop.
• Limitation: It can process element by element and only in forward direction.

Syntax :
foreach (elementType element in collection)
{
// code to execute on each element
}

Program to display element using for-each loop


using System;
class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
Console.WriteLine(num);
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 76


www.ameerpettechnologies.com

Array Class in C#

Array:
• In C#, there is a predefined Array class that provides a set of methods for working with
arrays.
• Here are some example programs that demonstrate how to use some of the methods of
the Array class:

Creating an array:
int[] numbers = new int[5]; // create an array of length 5

Initializing an array with values:


int[] numbers = { 1, 2, 3, 4, 5 }; // create and initialize an array with values

Setting the value of an element of an array:


int[] numbers = { 1, 2, 3, 4, 5 };
numbers[0] = 10; // set the value of the first element of the array to 10

Sorting an array:
int[] numbers = { 3, 1, 4, 2, 5 };
Array.Sort(numbers); // sort the array in ascending order

Reversing an array:
int[] numbers = { 1, 2, 3, 4, 5 };
Array.Reverse(numbers); // reverse the order of the elements in the array

Copying an array:
int[] numbers1 = { 1, 2, 3, 4, 5 };
int[] numbers2 = new int[5];
Array.Copy(numbers1, numbers2, 5); // copy the elements of numbers1 to numbers2

Convert Array to String to print easily:


• In C#, you can use the string.Join method to convert an array to a string so that you can
print it easily.
• Here is an example:
int[] numbers = { 1, 2, 3, 4, 5 };
string numbersString = string.Join(", ", numbers);
Console.WriteLine(numbersString);

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 77


www.ameerpettechnologies.com

Strings in C#

String:
• String is a sequence of characters
• String is an object in java.
• Strings must represent with double quotes.

Simple String representation:


public class Program{
public static void Main()
{
string str1 = "Hello"; // uses string keyword
String str2 = "Hello"; // uses System.String class
Console.WriteLine(str1);
Console.WriteLine(str2);
}
}

Construct the String object from Character array and display using foreach loop:
public class Program{
public static void Main()
{
char[] chars = {'H', 'e', 'l', 'l', 'o'};
string str1 = new string (chars);
String str2 = new String(chars);
foreach (char c in str1)
{
Console.WriteLine(c);
}
}
}

Find the length of the given string:


class Test {
public static void Main(string [] args)
{
string str = "C# Programming";
int length = str.Length;
Console.WriteLine("string: " + str);
Console.WriteLine("Length: "+ length);
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 78


www.ameerpettechnologies.com

Reverse a string:
string str = "hello world";
char[] arr = str.ToCharArray();
Array.Reverse(arr);
string reversedStr = new string(arr);
Console.WriteLine(reversedStr); // prints "dlrow olleh"

Convert a string to uppercase:


string str = "hello world";
string upperStr = str.ToUpper();
Console.WriteLine(upperStr); // prints "HELLO WORLD"

Convert a string to lowercase:


string str = "HELLO WORLD";
string lowerStr = str.ToLower();
Console.WriteLine(lowerStr); // prints "hello world"

Remove whitespace from a string:


string str = " hello world ";
string trimmedStr = str.Trim();
Console.WriteLine(trimmedStr); // prints "hello world"

Count the number of occurrences of a character in a string:


string str = "hello world";
char targetChar = 'o';
int count = 0;
foreach (char c in str){
if (c == targetChar){
count++;
}
}
Console.WriteLine(count); // prints "2"

Replace a substring with another string:


string str = "hello world";
string replacedStr = str.Replace("world", "universe");
Console.WriteLine(replacedStr); // prints "hello universe"

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 79


www.ameerpettechnologies.com

Immutability and Interpolation of Strings

String Immutability:
• In C#, a string is immutable.
• Immutability means that once a string object is created, its value cannot be changed.
• Any operation that modifies a string actually creates a new string object rather than
modifying the original string.

A
string str1 = "hello";
M
string str2 = str1;
E
str1 += " world"; E
Console.WriteLine(str1); // prints "hello world" R
Console.WriteLine(str2); // prints "hello" P
E
T
String interpolation:
• String interpoloation is a feature in C# that allows you to embed expressions inside T
string literals. E
C
• This makes it easier to create formatted strings that include values derived from variables
H
or expressions. N
O
Example programs: L
string name = "Amar"; O
int age = 23; G
I
string message = $"My name is {name} and I am {age} years old.";
E
Console.WriteLine(message); S

Formatting numeric values:


double pi = 3.141592653589793;
string message = $"The value of pi is approximately {pi:F2}.";
Console.WriteLine(message); // prints "The value of pi is approximately 3.14."

Note: F2 format specifier is used to format the value of pi with two decimal places.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 80


www.ameerpettechnologies.com

String Builder class

StringBuilder:
• StringBuilder class provides a convenient way to manipulate strings.
• It is Mutable String object.
• StringBuilder class providing methods to perform all string operations.

Appending Strings to a StringBuilder


using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder builder = new StringBuilder();
builder.Append("Hello");
builder.Append(" World");
Console.WriteLine(builder.ToString()); // Output: "Hello World"
}
}

Inserting Strings into a StringBuilder


using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder builder = new StringBuilder();
builder.Append("Hello World");
builder.Insert(5, ", ");
Console.WriteLine(builder.ToString()); // Output: "Hello, World"
}
}

Replacing Strings in a StringBuilder


using System;

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 81


www.ameerpettechnologies.com

using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder builder = new StringBuilder();
builder.Append("Hello World");
builder.Replace("World", "Universe");
Console.WriteLine(builder.ToString()); // Output: "Hello Universe"
}
}

Removing Characters from a StringBuilder


using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder builder = new StringBuilder();
builder.Append("Hello World");
builder.Remove(5, 6);
Console.WriteLine(builder.ToString()); // Output: "Hello"
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 82


www.ameerpettechnologies.com

Exception Handling

Introduction: During the compilation and execution time, there is a change of getting following
3 types of errors in C#

1. Compile time errors: Compiler raises error when we are not following language rules to
develop the code.
• Every Method should have return type.
• Statement ends with semi-colon;
• Invoking variable when it is not present

2. Logical Errors: If we get the output of code instead of Expected contains Logical error.
Expected Result
1 12345
12 1234
123 123
1234 12
12345 1

3. Runtime Errors: Runtime Error is called Exception which terminates the normal flow of
program execution.
• Handling invalid input by user
• Opening a file which is not present.
• Connect to database with invalid user name and password.

FormatException: It occurs if user enter invalid input while reading through Scanner.
using System;
public class Code
{
public static void Main()
{
Console.WriteLine("Enter 2 numbers : ");
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
int c = a+b;
Console.WriteLine("Sum is : " + c);
}
}

Output:
Enter 2 numbers :
abc
[System.FormatException: Input string was not in a correct format.]

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 83


www.ameerpettechnologies.com

Handling Exception using try-catch:


try block:
• It is used to place the code that may raise exception.
• When error occurs an exception object will be raised.

catch block:
• Exception object raised in try block can be collected in catch block to handle.

Handling InputMismatchException:
using System;
public class Program{
public static void Main(string[] args)
{
try
{
Console.WriteLine("Enter 2 numbers : ");
int x = Convert.ToInt32(Console.ReadLine());
int y = Convert.ToInt32(Console.ReadLine());
int z = x+y;
Console.WriteLine("Sum is : " + z);
}
catch(FormatException e)
{
Console.WriteLine("Exception : " + e.Message);
}
}
}

Note : Catch block executes only if exception raises in try block.

DivideByZeroException: we attempt to divide an integer by zero, which will cause a


DivideByZeroException to be thrown.
int a = 10;
int b = 0;
try{
int result = a / b;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: " + ex.Message);
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 84


www.ameerpettechnologies.com

IndexOutOfRangeException: we attempt to access an array element that is out of range (the


array only has 3 elements, but we try to access the 4th element at index 3). This will cause an
IndexOutOfRangeException to be thrown

int[] numbers = { 1, 2, 3 };
try
{
Console.WriteLine(numbers[3]);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Error: " + ex.Message);
}

ArgumentNullException: we attempt to access the Length property of a null string, which will
cause an ArgumentNullException to be thrown.

string str = null;


try
{
int length = str.Length;
}
catch (ArgumentNullException ex)
{
Console.WriteLine("Error: " + ex.Message);
}

FormatException: we attempt to convert a string that contains non-numeric characters to an


integer using int.Parse(), which will cause a FormatException to be thrown.
string str = "abc";

try
{
int num = int.Parse(str);
}
catch (FormatException ex)
{
Console.WriteLine("Error: " + ex.Message);
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 85


www.ameerpettechnologies.com

Handling Multiple exceptions : One try block can have multiple catch blocks to handle
different types of exceptions occur in different lines of code.

Program to read 2 numbers and perform division:


1. FormatException: If the input is invalid
2. DividByZeroException: If the denominator is zero

using System;
public class Program
{
public static void Main(string[] args)
{
try
{
Console.WriteLine("Enter 2 numbers : ");
int x = Convert.ToInt32(Console.ReadLine());
int y = Convert.ToInt32(Console.ReadLine());
int z = x/y;
Console.WriteLine("Result is : " + z);
}
catch(FormatException e1)
{
Console.WriteLine("Exception : " + e1.Message);
}
catch(DivideByZeroException e2)
{
Console.WriteLine("Exception : " + e2.Message);
}
}
}

We can handle Multiple exceptions in following ways:


Try with Multiple Catch blocks: It is useful to provide different message to different
exceptions.
try{
code…
}
catch(Exception1 e1){
}
catch(Exception2 e2){
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 86


www.ameerpettechnologies.com

catch object using Exception class: Same logic to handle all exceptions
try
{
Code….
}
catch(Exception e){
}

Using OR: Related exceptions can handle with single catch block
try
{
Code….
}
catch(Exception ex)
{
if(ex is FormatException || ex is DivideByZeroException)
{
Console.WriteLine("Exception " + ex.GetType());
}
}

Handling multiple exceptions with single catch block:


using System;
public class Program
{
public static void Main(string[] args)
{
try
{
Console.WriteLine("Enter First Number");
int a = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Second Number");
int b = int.Parse(Console.ReadLine());
int res = a / b;
Console.WriteLine("Result: " + res);
}
catch (Exception e)
{
Console.WriteLine("Exception : " + e.Message);
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 87


www.ameerpettechnologies.com

Handling exceptions with Logical OR(||) operator:


using System;
public class Program{
public static void Main(string[] args){
try {
Console.WriteLine("Enter 2 integers to add : ");
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
int c = a/b;
Console.WriteLine("Result = " + c);
}
catch(Exception ex){
if(ex is FormatException || ex is DivideByZeroException)
{
Console.WriteLine("Exception " + ex.GetType());
}
}
}
}

Finally block:
• Finally, block is used to close resources (file, database etc.) after use.
• Finally block executes whether or not an exception raised.
using System;
public class Program{
public static void Main(string[] args)
{
try{
int a=10, b=0;
int c=a/b;
Console.WriteLine("Try block");
}
catch (Exception){
Console.WriteLine("Catch block");
}
finally
{
Console.WriteLine("Finally block");
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 88


www.ameerpettechnologies.com

Why closing statements belongs to finally block?


• Resource releasing logic must be executed whether or not an exception raised.
• For example, in ATM Transaction - the machine should release the ATM card in success
case or failure case.

Open and close the file using finally block:


using System;
using System.IO;
public class Program
{
public static void Main(string[] args)
{
StreamReader sr = null;
try
{
sr = new StreamReader("d:/new.txt");
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
catch (Exception)
{
Console.WriteLine("Exception : No such file");
}
finally
{
if(sr != null)
{
sr.Close();
Console.WriteLine("File closed");
}
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 89


www.ameerpettechnologies.com

Custom Exceptions: You can create custom exceptions by creating a new class that derives
from the System.Exception class

public class MyCustomException : Exception


{
public MyCustomException()
{
}
public MyCustomException(string message): base(message)
{
}
}

In this example, MyCustomException is a class that derives from the Exception class. It has
three constructors that take different parameters:
4. The first constructor takes no arguments and can be used to create an instance of the
exception with a default message.
5. The second constructor takes a string argument that represents the error message for
the exception.

Throw keyword:
• To throw a custom exception, you can simply create an instance of your custom
exception class and throw it using the throw keyword:
o throw new MyCustomException("Something went wrong.");

You can catch this exception using a try-catch block and handle it accordingly:
try
{
// Some code that may throw MyCustomException
}
catch (MyCustomException ex)
{
// Handle the exception
}

InvalidAgeException:
• Define a method is used to check the person eligible for Vote or Not
• If the age is not sufficient, throw InvalidAgeException object.
• We need to handle the exception using try-catch blocks while invoking method.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 90


www.ameerpettechnologies.com

using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Enter Age : ");
int age = Convert.ToInt32(Console.ReadLine());
try
{
Person.canVote(age);
}
catch(InvalidAgeException e)
{
Console.WriteLine("Exception : " + e.Message);
}
}
}
public class Person
{
public static void canVote(int age)
{
if(age>=18)
{
Console.WriteLine("Can vote");
}
else
{
InvalidAgeException err = new InvalidAgeException("Invalid Age");
throw err;
}
}
}
public class InvalidAgeException : Exception
{
public InvalidAgeException(string name): base(name)
{
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 91


www.ameerpettechnologies.com

LowBalanceException:
• Define Account class with initial balance.
• Define withdraw method.
• Raise exception if the sufficient amount is not present while withdrawing from account.

using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Enter balance in account : ");
int bal = Convert.ToInt32(Console.ReadLine());

Account acc = new Account(bal);


Console.WriteLine("Balance is : " + acc.GetBalance());

Console.WriteLine("Enter withdraw amount : ");


int amt = Convert.ToInt32(Console.ReadLine());
try
{
acc.withdraw(amt);
}
catch(LowBalanceException e)
{
Console.WriteLine("Exception : " + e.Message);
}
Console.WriteLine("Balance is : " + acc.GetBalance());
}
}

public class Account


{
private int balance;
public Account(int balance)
{
this.balance = balance;
}
public int GetBalance()
{
return this.balance;
}
public void withdraw(int amt)
{

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 92


www.ameerpettechnologies.com

if(amt <= this.balance)


{
Console.WriteLine("Collect cash");
this.balance = this.balance - amt;
}
else
{
LowBalanceException err = new LowBalanceException("Invalid Age");
throw err;
}
}
}

public class LowBalanceException : Exception


{
public LowBalanceException(string name): base(name)
{
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 93


www.ameerpettechnologies.com

Multi-threading

Multi-threading is a process of executing two or more threads (programs) simultaneously to


utilize the processor maximum.

Multi-tasking:
• We can implement multi-tasking in two ways.
o Program(process) based
o Sub program (thread) based.

Single Threaded application:


• The following example shows the execution process of program without threading.

using System;
public class Program
{
public static void Main()
{
First.print1to50();
Second.print50to1();
}
}
public class First
{
public static void print1to50()
{
for (int i = 1; i <= 50; i++)
{
Console.WriteLine("i value : " + i);
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 94


www.ameerpettechnologies.com

public class Second


{
public static void print50to1()
{
for (int j = 50; j >= 1; j--)
{
Console.WriteLine("j value : " + j);
}
}
}

sleep():
• It is a static method define in Thread class.
• It is used to stop the thread execution for specified number of milliseconds.
using System;
using System.Threading;
public class Program{
static void Main(string[] args)
{
First.print1to10();
Second.print10to1();
}
}
public class First{
public static void print1to10()
{
for (int i=1; i<=10; i++)
{
Console.WriteLine("i value : " + i);
Thread.Sleep(1000);
}
}
}
class Second{
public static void print10to1()
{
for(int j=10; j>=1; j--)
{
Console.WriteLine("j value : " + j);
Thread.Sleep(1000);
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 95


www.ameerpettechnologies.com

Define Custom thread:


• We need to pass the method(thread logic) as an argument by starting the new Thread as
follows

Thread t = new Thread(new ThreadStart(method name));

Thread Life Cycle: Every thread has undergone different states in its Life.
1. New State: Thread object created but not yet started.
2. Runnable State: Thread waits in queue until memory allocated to run.
3. Running State: Threads running independently once they started.
4. Blocked State: The thread is still alive, but not eligible to run. A
5. Terminated State: A thread terminates either by complete process or by occurrence of M
error E
E
R
P
E
T

T
E
C
H
N
O
L
O
using System;
G
using System.Threading;
I
public class Program
E
{
S
static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(First.print1to10));
Thread t2 = new Thread(new ThreadStart(Second.print10to1));
t1.Start();
t2.Start();
}
}
public class First
{
public static void print1to10()
{
for (int i=1; i<=10; i++)

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 96


www.ameerpettechnologies.com

{
Console.WriteLine("i value : " + i);
Thread.Sleep(1000);
}
}
}
public class Second
{
public static void print10to1()
{
for(int j=10; j>=1; j--)
{
Console.WriteLine("j value : " + j);
Thread.Sleep(1000);
}
}
}

join():
• An instance method belongs to Thread class.
• It stops the current the thread execution until joined thread execution completes.

Consider First thread is calculating sum of first N numbers and second thread has to display
the result. The Second thread has to wait until First thread completes calculation.

using System;
using System.Threading;
public class Program
{
public static int n;

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 97


www.ameerpettechnologies.com

static void Main(string[] args)


{
Console.WriteLine("Enter n value : ");
Program.n = Convert.ToInt32(Console.ReadLine());
Thread t = new Thread(new ThreadStart(Calculation.find));
t.Start();
t.Join();
Console.WriteLine("Sum of First : " + n + " numbers is : " + Calculation.sum);
}
}
public class Calculation
{
public static int sum = 0;
public static void find()
{
for(int i=1; i<=Program.n; i++)
{
Calculation.sum = Calculation.sum + i;
}
}
}

Abort() method:
• The Abort() method is used to terminate the thread.
• It raises ThreadAbortException if Abort operation is not done.

using System;
using System.Threading;
public class MyThread
{
public void Thread1()
{
for (int i=0; i<10; i++)
{
Console.WriteLine(i);
Thread.Sleep(200);
}
}
}
public class Program
{
public static void Main()

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 98


www.ameerpettechnologies.com

{
Console.WriteLine("Start of Main");
MyThread mt = new MyThread();
Thread t1 = new Thread(new ThreadStart(mt.Thread1));
Thread t2 = new Thread(new ThreadStart(mt.Thread1));
t1.Start();
t2.Start();
try
{
t1.Abort();
t2.Abort();
}
catch (ThreadAbortException tae)
{
Console.WriteLine(tae.ToString());
}
Console.WriteLine("End of Main");
}
}

Thread Synchronization:
• Synchronization is the concept of allowing thread sequentially when multiple threads
trying to access the resource.
• We implement synchronization using ‘synchronized’ keyword.
• We can synchronize either Block or Method.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 99


www.ameerpettechnologies.com

using System;
using System.Threading;
public class LockDisplay
{
public void DisplayNum()
{
lock (this)
{
for (int i = 1; i <= 5; i++)
{
Thread.Sleep(100);
Console.WriteLine("i = {0}", i);
}
}
}
}
class Example
{
public static void Main(string[] args)
{
LockDisplay obj = new LockDisplay();
Thread t1 = new Thread(new ThreadStart(obj.DisplayNum));
Thread t2 = new Thread(new ThreadStart(obj.DisplayNum));
t1.Start();
t2.Start();
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 100
www.ameerpettechnologies.com

C# Stream IO

Stream:
• The Stream abstract base class supports reading and writing bytes.
• All classes representing streams inherit from the Stream class.
• Stream comes under the System.IO

Reading file character by character:


using System;
using System.IO;
public class Program
{
public static void Main(string[] args)
{
StreamReader sr = null;
try
{
sr = new StreamReader("d:/new.txt");
int ch;
while ((ch = sr.Read()) != -1)
{
Console.WriteLine((char)ch);
}
}
catch (Exception)
{
Console.WriteLine("Exception : No such file");
}
finally
{
if(sr != null)
{
sr.Close();
Console.WriteLine("File closed");
}
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 101
www.ameerpettechnologies.com

using() method: using statement to ensure that the StreamReader object is properly disposed
of when we're finished with it.

Reading File character by character:


using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
try
{
using (StreamReader reader = new StreamReader("example.txt"))
{
while (!reader.EndOfStream)
{
int character = reader.Read();
if (character == -1)
{
break;
}
Console.Write((char)character);
}
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}

Reading File Line by Line: The ReadLine() method returns a string that represents the next line
in the file, or null if the end of the file has been reached.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
try
{
using (StreamReader reader = new StreamReader("example.txt"))

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 102
www.ameerpettechnologies.com

{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}

Copy contents of one file into another file:


using System;
using System.IO;
class Program{
static void Main(string[] args)
{
try
{
using (StreamReader reader = new StreamReader("source.txt"))
{
using (StreamWriter writer = new
StreamWriter("destination.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
writer.WriteLine(line);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 103
www.ameerpettechnologies.com

Serialization and De-Serialization

Serialization:
• Serialization is the process of converting an object into a stream of bytes.
• Serialized file can be stored on disk, sent over a network, or otherwise transmitted as a
binary data.
• In C#, we can use the BinaryFormatter class to perform serialization.

Here's an example:
using System;
using System.IO;
A
using System.Runtime.Serialization.Formatters.Binary; M
class Person E
{ E
public string Name { get; set; } R
P
public int Age { get; set; }
E
} T
class Program
T
{
E
static void Main(string[] args) C
{ H
Person person = new Person { Name = "John Doe", Age = 30 }; N
BinaryFormatter formatter = new BinaryFormatter(); O
using (FileStream stream = new FileStream("person.bin", FileMode.Create)) L
O
{
G
formatter.Serialize(stream, person); I
} E
Console.WriteLine("Serialization complete."); S
}
}

De-serialization
• De-serialization is the process of converting a stream of bytes back into an object.
• In C#, we can use the BinaryFormatter class to perform de-serialization.

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 104
www.ameerpettechnologies.com

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream("person.bin", FileMode.Open))
{
Person person = (Person)formatter.Deserialize(stream);
Console.WriteLine("Name: " + person.Name);
Console.WriteLine("Age: " + person.Age);
}
Console.WriteLine("De-serialization complete.");
}
}

Contact for Online Classes: +91 – 911 955 6789 / 7306021113 105

You might also like