C# Material
C# Material
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
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
Structure of C# Program
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.
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();
}
}
}
C# naming conventions
Use PascalCase for class names, method names, and property names.
// Recommended
public void CalculateTotalCost(double productCost, int quantity)
{
double totalCost = productCost * quantity;
Console.WriteLine($"The total cost is {totalCost}");
}
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; }
}
Syntax:
datatype identity = value;
Examples:
String name = “Amar”;
int age = 23;
char gender = ‘M’;
bool married = false;
double salary = 35000.00;
Identifier rules:
• Identifier is a name given to class, method, variable etc.
• Identifier must be unique
• Identifier is used to access the member.
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);
}
}
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.
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
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);
}
}
double d = Convert.ToDouble(Console.ReadLine());
}
}
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);
}
}
Console.WriteLine("Details : " + id + " , " + name + " , " + gender + " , " +
salary + " , " + married);
}
}
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
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
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.
Modify operators:
Logical Operators
• A logical operator is primarily used to evaluate multiple expressions.
• Logical operators return boolean value.
• Operators are && , || and !
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));
}
}
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.
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);
}
}
Condition:
a >= 0
Condition:
a == 0
Condition:
a ==b
Condition:
a>b
Condition:
a*a == b
Condition:
a+b == 10 ;
Condition:
n % 3 == 0
Condition:
n % 2 == 0
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:
(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
Condition:
quantity%12 == 0
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:
n % 3 == 0 && n % 5 == 0
Condition:
n >= 30 && n <= 50
Condition:
m1>=35 && m2>=35 && m3>=35 && m4>=35 && m5>=35
Condition:
ch == ‘a’ || ch == ‘e’ || ch== ‘i’ || ch==’o’ || ch==’u’
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:
a!=b && b!=c && c!=a
Control Statements
Sequential statements:
• Statement is a line of code.
• Sequential Statements execute one by one from top-down approach.
if(condition)
{
Logic;
}
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;
}
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;
}
class Code
{
public static void Main()
{
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");
}
}
}
Introduction to Loops
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.
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.
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.
while(condition)
{
statements;
}
while(n!=0)
{
sum = sum + n%10;
n=n/10;
}
Console.WriteLine("Sum of digits : " + sum);
}
}
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");
}
}
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
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
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
Do-While Loop
do-while: Executes a block at least once and continue iteration until condition is false.
do
{
statements;
} while(condition);
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");
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.
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;
}
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).
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.
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.
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;
}
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.
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;
}
}
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
Constructor:
• Defining a method with Class-Name.
• Constructor Not allowed return-type.
class Employee
{
public Employee()
{
Console.WriteLine("Object created");
}
}
Instance Method:
• Defining a method without static keyword.
• We must invoke the method using object-reference.
Instance Variables:
• Defining a variable inside the class and outside to methods.
• Instance variables get memory inside every object and initializes with default values.
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
}
}
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.
class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
obj.SetNum(10);
obj.ShowNum(); // Output: num = 10
}
}
class Program
{
static void Main(string[] args)
{
MyDerivedClass obj = new MyDerivedClass();
obj.SetNum(10);
obj.ShowNum(); // Output: num = 10
}
}
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;
}
}
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());
}
}
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();
}
}
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
class A{
....
}
class B : A{
....
}
class C : B{
....
}
class A{
....
}
class B : A{
....
}
class C : A{
....
}
Interface A{
}
Interface B{
}
Class C : A, B{
}
Interface A{
}
Interface B{
}
Interface C : A, B{
}
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
}
}
}
}
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.
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();
}
}
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();
}
}
Polymorphism:
• Polymorphism is the concept where object behaves differently in different situations.
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);
}
}
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();
}
}
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();
}
}
Down casting: The concept of collecting Child object address back to Child type reference
variable from Parent type.
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.
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 :
}
}
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();
}
}
using System;
abstract class Parent
{
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();
}
}
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();
}
Upcasting: object reference of implemented class storing into Interface type variable
class A{
}
class B{
}
class C : A, B{
}
class A{
}
interface B{
}
class C : A, B{
}
interface A{
}
interface B{
}
class C : A, B{
}
using System;
interface A
{
void m1();
}
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();
}
}
Objects - Relations
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.
Is-A relation: Is-A relationship defines the relationship between two classes in which one class
extends another class.
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.
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.
Many to One: One Menu Item can be ordered by any number of Customers
class Author
{
String authorName;
int age;
String 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();
}
}
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[];
}
}
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);
}
}
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]);
}
}
}
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);
}
}
Syntax :
foreach (elementType element in collection)
{
// code to execute on each element
}
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
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
Strings in C#
String:
• String is a sequence of characters
• String is an object in java.
• Strings must represent with double quotes.
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);
}
}
}
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"
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
Note: F2 format specifier is used to format the value of pi with two decimal places.
StringBuilder:
• StringBuilder class provides a convenient way to manipulate strings.
• It is Mutable String object.
• StringBuilder class providing methods to perform all string operations.
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"
}
}
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.]
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);
}
}
}
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.
try
{
int num = int.Parse(str);
}
catch (FormatException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
Handling Multiple exceptions : One try block can have multiple catch blocks to handle
different types of exceptions occur in different lines of code.
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);
}
}
}
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());
}
}
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");
}
}
}
Custom Exceptions: You can create custom exceptions by creating a new class that derives
from the System.Exception class
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.
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)
{
}
}
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());
Multi-threading
Multi-tasking:
• We can implement multi-tasking in two ways.
o Program(process) based
o Sub program (thread) based.
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);
}
}
}
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);
}
}
}
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++)
{
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;
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()
{
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.
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
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 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);
}
}
}
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 103
www.ameerpettechnologies.com
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