C#_notes
C#_notes
DOT NET
.net (network enabled technology).
.net is a framework or a software product developed by Microsoft.
.net was developed to develop a different type of applications.
To develop the application .net support 30+ languages like C#, F#, VB etc.
In marked C# is most preferable language.
Types of applications.
Desktop app- C
Web app – JAAVASCRIPT, VB, PG
Mobile app- Dot net
Note: Using dot net we can develop all types of applications.
IL (intermediate language)
Just in time compile
CLR (common language runtime)
Machine code
Source code:
A code which is written by programmer in plain English text with programming syntax.
C # file was saved with cs.
C # compile is programming software which is convert the source code into IL (intermediate
language).
IL (INTERMEDIATE LANGUAGE)
It is also known as MSIL.
MSIL is an intermediate language & it contains byte code which is using to execute.
MSIL found in exe-file.
JUST IN TIME COMPILER(JIT)
JIT is responsible for conversion of IL into machine code.
COMMON LANGUAGE RUNTIME(CLR)
CLR is main component of the .net frame
CLR is runtime environment which is responsible for the execution of c # & other language
programs in .net environment.
MACHINE CODE
It is also known as binary code & negative code & it is the machine understandable code (0,1)
Which can be executed by machine.
First program in C #
How to write first program in c #
To write a c # program we require 3 components
1. Class
2. Main method
3. Printing statement
I. Class:
Class is a blue print of a program.
It contains method & variables.
To create a class, we need to use class keyword & class name with body
Syntax
Class keyword class name
{
body
}
II. Main method:
It is a starting point of the C # program.
It is heart to CLR without main method program will not execute.
But it can compile.
Static void main (string [] args)
| | | |
Non access keyword returning type name of the method string array
III. Printing statement:
Console. WriteLine.
Program
Class hello
{
Static void main (string [] args)
{
Console. WriteLine (“hello world”);
}
}
Identifiers :Identifiers:
A name (variable name / class name/ method name) is known as identifier.
Rules:
Identifiers allow alphabets (A-Z/a-z), numbers (0-9) & special characters ( _ ).
C # is case sensitive language.
Don’t start with number.
C # does not allow spaces.
C # does# does not allow duplicates.
Don’t use resaved words as identifiers.
Data types:
Data type specifies the type & range of the data.
In C# they are different types of data types.
And there are mainly 7 data types.
1 byte = 8 bits. (data was measured in bytes)
Variables:
A variable is a container which can store the values while executing the program.
A data was store in the name of variable.
Assigning the datatype is must for variable.
syntax: Datatype Variable name=data;
int i = 8;
datatype variable data
they are 3 of variables
1. Instance / global variable.
2. Local variable.
3. Static variable.
Program
Static void main (string [] args) {
String name=” Ramya”;
Double salary=65.16547564;
Int id=8;
Long mobile no=464125864;
Bool status= true;
Console. WriteLine(“name”) =name
Console. WriteLine(name)=Ramya
Console. WriteLine(id)=8
Console. WriteLine(status)=true
Console. WriteLine (8) =8
Console. WriteLine (“8” +8) =88
Console. WriteLine (8+8) =16
Console. WriteLine(id+8) =16
Console. WriteLine (“salary =” +salary) =salary=65745231
Type casting
Converting from one datatype to another datatype is known as type casting.
It is also known as type conversion.
Example: char int
Type casting divided into two types
1. Implicit type casting
2. Explicit type casting
Implicit type casting Explicit type casting
Converting from small datatype to large Converting from large datatype to small
datatype datatype
Here source should be less than destination Here source should be more than destination
It can do automatically It can be done manually by adding code.
Console. WriteLine(points) }
Console. WriteLine(grade);}
Example:
Char Ch=’a’
Int i= Convert.ToInt32(Ch);
Long l=Convert.ToInt64(Ch);
Operators
Operators are symbols like +, -, /, % etc
Operations between 2 operands.
Ex: a=20 b=30 b+c=50
In c# there are mainly 6 operators
1. Arthematic operator
2. Relational operator
3. Logical operator
4. Unary operator
5. Assignment operator
6. Ternary operator
1) Arithmetic operator:
This operator is used to perform mathematical expressions
(plus) + -addition
(minus)- - subtraction
(times)* -multiplication
(by) / - division (coefficient)
(modulus)% -division (reminder)
Example:
{
Svm(s [] a)
{
Int a=100, b=20;
Console. WriteLine (a+b) ; =120
Console. WriteLine(a-b); =80
Console. WriteLine(a*b); =2000
Console. WriteLine(a/b) =5
Console. WriteLine(a%b) =0
2) Relational operators:
These operators are used to check the relation between 2 operands.
This operator returns Boolean values (true/false)
(==) equals checks L.H.S & R.H.S.
(! =) no equals check L.H.S & R.H.S
(<) less than
(>) greater than
(<=) less than or equal
(>=) greater or equal
Example:
static void Main (string [] args)
{
int a = 10;
int b = 20;
int c = 10;
int d = 20;
Console. WriteLine(a>=c);
Console. WriteLine(a<=b);
Console. WriteLine(a==b);
Console. WriteLine(d==c);
}
3) Assignment operators:
These operators are used to assign the values from R.H.S & L.H.S
= equals tic *= time & equals
+= plus & equals /= divide & equals
-= minus & equals %= module & equals
4) Ternary operators:
These operators are used to involve of if else condition
5) Logical operators:
This operand checks the logic between 2 operators. It returns Boolean values(true/false)
// - logical or
&& - logical and
Example:
static void Main (string [] args)
{
int a = 10;
int b = 20;
int c = 10;
int d = 20;
Console. WriteLine(a==c||b==d);
Console. WriteLine(a==c||a==b);
Console. WriteLine(c==b||c==d);
Console. WriteLine(a==c&&b==d);
}
6) Unary operators:
These operators are using to increment or decrement the value.
++ value - pre increment
+ + (increment)
Value ++ - post increment
if while break
These statements are used to execute the statement when the condition satisfies>
They are divided into 5 types
If
If else
Else if
Nested if
Switch
[1.] if condition : [1.] Nested if :
It is a basic condition [Link] is a block of A If block inside another if block is known as
statement with condition. When the condition is nested if.
true, if block will execute. When the condition is Syntax:
false if block will skip. If(condition)
Syntax: {
If(condition) If(condition)
{ {
statement }
}
} Example:
Example: static void Main (string [] args)
static void Main (string [] args) {
{ Console. WriteLine ("enter time");
int time = Convert.ToInt32([Link]());
Console. WriteLine ("enter age");
int age = if (time>=7)
Convert.ToInt32([Link]()); {
if ( age >=18) if(time<=10)
{ {
Console. WriteLine("eligible"); Console. WriteLine ("good morning");
} } } }
}
1.[2.] Else if : 1.[2.] If else condition:
It is a block of statement and it is an odd on It is a block of statement both if and if else. If
to the if else condition. contains condition else without condition.
When we have multiple conditioncondition, When the if condition is true if block will
we can use else if condition. execute. When the block fails then else block
Syntax: will execute
If (condition) Syntax:
{ If (condition)
}
Else if (condition) {
{
} }
Else if (condition) Else
{ {
}
Else }
{ Example:
} static void Main (string [] args)
Example: {
static void Main (string [] args)
{ Console. WriteLine ("enter age");
Console. WriteLine ("enter a int num =
number"); Convert.ToInt32([Link]());
int i = if (num > 0 && num % 2==0)
Convert.ToInt32([Link]());
if (i%3==0 && i%5==0) {
{ Console. WriteLine("even");
Console. WriteLine ("fizz buzz"); }
} else
else if (i%3==0) {
{ Console. WriteLine ("not an even");
Console. WriteLine("fizz"); }
} }
else if (i%5==0)
{
Console. WriteLine("buzz");
}
else
{
Console. WriteLine (" i");
}
}
2.[3.] Switch:
A switch statement is a block of code which
contain multiple cases with break.
Syntax:
switch (expression)
{
Case value;
-----------
Break;
Case value;
-----------
Break;
Case value;
-----------
Break;
}
Example:
static void Main(Main (string[string [] args)
{
Console. WriteLine ("choose a month");
int month =
Convert.ToInt32([Link]());
switch (month)
{
case 1:
Console. WriteLine("January");
break;
case 2:
Console. WriteLine("February");
break;
case 3:
Console. WriteLine("march");
break;
case 4:
Console. WriteLine("April");
break;
case 5:
Console. WriteLine("may");
break;
case 6:
Console. WriteLine("June");
break;
}
}
}
Example:
2. Do While loop:
It is a looping statement executes the statement until condition satisfy.
Here after executing the statement condition will check.
Syntax:
Do
{
}
While(condition);
Example:
static void Main(Main (string[string [] args)
{
Console. WriteLine ("number of times");
int i = Convert.ToInt32([Link]());
do
{
Console. WriteLine ("welcome to the class");
n++;
}
while (n <= 10)
}
3. Do While loop:
It is a basic & simple looping statement.
It is a looping statement initiate the statement until condition satisfy.
Here initialisation, condition & ++ & -- follows in single lines.
Syntax:
For (initialization; condition; ++ / --)
Example:
static void Main (string [] args)
{
Console. WriteLine ("enter a number");
int n = Convert.ToInt32([Link]());
while(n>0)
{
rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
}
if(i==rev)
{
Console. WriteLine ("palindrome
number");
}
else
{
Console. WriteLine ("not a
palindrome number");
}
}
4. Nested for:
A for inside another for loop. it can be used for matrix representation.
Syntax:
For (initialization; condition; ++ / - -)
{
For (initialization; condition; + + / - -)
{
} }
Print pattern: (1 2 3 Print pattern: (* * * *
456 ** **
7 8 9) ****
static void Main(Main (string[string [] args) * * * *)
{ static void Main(Main (string[string [] args)
int n = 1; {
for (int i=0; i<3; i++)
{ for (int i=1; i<=4; i++)
for (int j=0; j<3; j++) {
{ for (int j=1; j<=4; j++)
Console. Write(n+""); {
n++; Console. Write ("*");
}
Console. WriteLine (); }
} Console. WriteLine ();
} }
}
Print pattern: (1 2 3 4 Print pattern: (1 1 1 1
1234 2222
1 2 3 4) 3 3 3 3)
static void Main (string [] args) static void Main (string [] args)
{ {
for (int i=1; i<=3; i++) for (int i=1; i<=3; i++)
{ {
for (int j=1; j<=4; j++) for (int j=1; j<=4; j++)
{ {
Console. Write(j); Console. Write(i);
}
Console. WriteLine (); }
Console. WriteLine ();
} }
Print pattern: (1 2 3 Print pattern: (*
246 **
3 6 9) ***
static void Main(Main (string[string [] args) * * * *)
{ static void Main(Main (string[string [] args)
for(for (int i=1; i<=3;i3; i++) {
{ for(for (int i=1; i<=4;i4; i++)
for(for (int j=1; j<=3; j++) {
{ for(for (int j=1; j<=i; j++)
Console. Write(Write (i*j )j); {
} Console. Write(Write ("*");
Console. WriteLine(WriteLine (); }
} Console. WriteLine(WriteLine ();
} } }
Print pattern: (* * * * Print pattern: (* * * *
*** ***
** **
*) *)
static void Main(Main (string[string [] args) static void Main(Main (string[string [] args)
{ {
for(for (int i=1; i<=4;i4; i++) for (int i = 1; i <= 4; i++)
{ {
for(for (int j=i; j<=4; j++) for (int j = 1; j <= i; j++)
{ {
Console. Write(Write ("*"); [Link](" ");
} }
Console. WriteLine(WriteLine (); for (int k = i; k <= 4; k++)
} {
} [Link]("*");
}
Console. WriteLine(WriteLine ();
}
1. Break:
This is used to stop the execution when condition is true.
Syntax:
Break ;
Example:
Class break
{
static void Main (string [] args)
{
For (int i=1; i<=10; i++)
{
if (i==5)
{
break;
}
Console. WriteLine(i); } }
2. Continue:
It is used to skip the execution when condition true.
Example:
Print 1 to 10 by skipping 5 Skip numbers divisible by 5 from 1-100
static void Main (string [] args) static void Main (string [] args)
{ {
For (int i=1; i<= 10; i++) For (int i=1; i<=100; i++)
{ {
if (i==5) if (i%5==0)
{ {
continue;
continue;
}
} Console. WriteLine(i);
Console. WriteLine(i); }
} }
}
ARRAY
Arrays are collection of similar data types.
Arrays’ are used to store multiple values in a single variable instead of declaring separate variables
for each value.
They store the values in index based .
Index start from 0.
Index ends with length-1.
Advantages :
Store multiple values.
Random access.
More efficient.
Easy to use.
Disadvantages:
fixed in size
no predefined methods for adding & removing elements.
Types of arrays :
one dimensionary (1D)
two dimensionary (2D)
three dimensionary (3D)
jagged array
One dimensionary:
It is a simplest type of array that contains only one row for storing data.
Declaring array: two ways
b. Char [] Ch={‘a’,’b’,’c’};
Console. WriteLine (Ch. Length);
Example: Find large element in array
Int [] a= {4,6,8,9,10,3}; Int [] a= {1,6,8,4};
For (int i=0; i<a. length; i++) Int large = a [0];
{ For (int i=1; i<a. length; i++)
Console. WriteLine(a[i]); {
} If (large < a[i])
{
Char [] a= {‘r’,’a’,’m’,’y’,’a’}; Large=a[i];
for (int i=0; i<Ch. Length; i++) }
{ }
Console. WriteLine (Ch[i]); Console. WriteLine(large); }
}
2-dimension array:
2-D array represent matrix types it means it can store data in multiple rows & columns.
Syntax:
Datatype [,] array name = new datatype [rows, columns];
Example:
class two d
{
Svm (s [] args)
{
//declaring
Int [,] a= new int [2,3];
// adding
a [0,0] = 1;
a [0,1] =2;
a [1,2] =3;
//getting
Console. WriteLine (a [0,0]);
Literal method:
Int [,] a = {{1,2,3}, {2,3,4}, {6,8,9}};
For (int i=0; i<3; i++)
{
For (int j=0; j<3; j++)
{
[Link] (a [i, j]);
}
Console. WriteLine (); }
3 D array:
It stores the data in multiple tables with rows & columns.
Syntax:
Datatype [,,] array name =new data type (table, rows, columns);
Int [,,] a = new int (2,3,3);
A[0,0,0]=1;
B [0,1,1] =2;
{
Console. WriteLine (a [1,2,0]); }
Literal method:
{
int[,,] a = {{{ 1, 2, 3}, {1, 2, 3 } }, { { 4, 5, 6 }, { 6, 7, 8 } } };
for (int t=0; t<2; t++)
{
For (int i=0; i<2; i++)
{
For (int j=0; j<3; j++)
{
Console. Write(a[t,i,j]);
}
Console. WriteLine ();
}
Console. WriteLine ();
}
For each
It is a coding statement executes the statement until the array length reach.
Syntax:
Foreach (datatype variable in array name)
{
}
Example:
int [] a = {1, 2, 3, 4};
foreach (int i in a)
{
Console. WriteLine(i);
}
Jagged array:
In this array columns should differ with each row
Syntax:
Datatype [] [] array name= new datatype (row count) [];
Int [] [] a= new int [3] [];
a [0] =new int [] {1,2,3};
a [1] = new int [] {5,4};
a [2] =new int [] {1,4,8};
Console. WriteLine (a [1][1]); }
Example:
Int [] [] a=new int [3] [];
a [0] =new int [] {1,2,3};
a [1] =new int [] {5,4};
a [2] =new int [] {1,4,5};
Array exception:
In array while retrieving data of index value out the declared index then arrayindexoutofrangeexception.
Exception is a runtime error.
Oops is a concept to achieve code security, code reusability & code readability.
Before Oops:
No code security
No code reusability
No code readability
Oops is not a single concept ,concept, it contains 4 principles (4 pillars)
Abstraction
Encapsulation
Inheritance
Polymorphism
Oops concepts:
Class
Constructor & object
Method
Encapsulation
Inheritance
Polymorphism
Abstraction
1. Class:
It is a blueprint of a program. It contains variables ,variables, constructors & method.
To create a class, we need to use class keyword & class name with body.
Syntax:
Class keyword class name
{
}
Example:
Class demo
{
}
2. Constructor:
It is ais a special type of method & no need to call with object which creating the object it will call
directly.
Constructor looks like a method & name should be similar to the class name & without written type.
Creating constructor is optional.
If you are not creating constructor CLR will create default constructor.
Syntax:
Public class demo
{
Public demo ( )()
{
}
3. Object:
It is an instance of access of a class. By using object, we can access all the properties of the
class .class.
Object represents real world entities.
To create object, we need to use new keyword with the constructor.
Syntax:
Class name object name = new classnew class name ( )();
Example:
Demo d = new= demonew demo ( )();
}
Syntax for to call method:
[Link] ( )();
Call by value:
When we calling a method by passing value / parameter is known as call by value.
Example:
Class number finding
{
public void evenfind (int n)
{
if(n%2==0)
{
Console. WriteLine("even");
}
else
{
Console. WriteLine(WriteLine ("not even");
}
}
Class program
{
static void Main(Main (string[string [] args)
{
number finding nffinding nf = new numberfindingnew numberfinding ( )():
[Link](4);
} }
Example:
Class app
{
Public void registervoid (register (string namestring ,name, long mobno, stringmobno, addstring add)
{
Console. WriteLine(WriteLine (“name” + name);
Console. WriteLine(WriteLine (“mobno” + mobno);
Console. WriteLine(WriteLine (“add” +add);
}
}
Variables:
It is a container it can store the value while executing the program. A data was stored in the name of
variable. Assigning the data type must for variable.
There are three types of variables
Instance / global variable
Local variable
Static variable
Example:
public class demo class program
{ {
int i = 10; 10; // instance variable static void Main(Main (string[string [] args)
public int a = 20; /20; //global variable {
demo d = new demo(demo ();
public void display ( )() [Link]();
{ [Link]();
int j = 20; /20; //local variable
Console. WriteLine(j); Console. WriteLine(WriteLine (d.i); //
Console. WriteLine(i); (error)
} Console. WriteLine(WriteLine (d.a); //20
public void show ( )() }
{ }
Console. WriteLine(i);
Console. WriteLine(a);
Console. WriteLine(j);
}
}
Note: we can call instance by object
Example:
Class bank
{
Public int balance ;balance;
Public bankPublic bank (int initial bal)
{
Balance =Balance = initial bal;
Console. WriteLine(WriteLine (“your account created with “ +“+ initial bal + “rps”);
}
Public void deposit (int dptbal)
{
Balance=balance+dptbal;
Console. WriteLine(WriteLine (“after deposit :deposit: balance=” +balance);
}
Public void withdrawwithdraws (int wdbal)
{
If (wdbal < = balance)
{
Balance = balance -wdbal;
Console. WriteLine(WriteLine (“after withdraw :withdraw: balance =” +balance);
}
Else{Else {
Console. WriteLine(WriteLine (“insufficient balance”);
}
}
4.[5.] Inheritance:
It is a concept one class acquires another class properties is known as inheritance.
Here we can achieve code reusability.
It represents IS A relationshipA relationship.
It means parent child relation.
Here child can access the parent class properties.
Parent cannot access the child class properties
To build a relation between two classes we need to use “ :“: “
}
}
Types of inheritance:
i. Single
ii. Multilevel
iii. Hierarchical
iv. Hybrid
v. Multiple
i. Single:
One parent having one child class is known as single inheritance.
Example:
Class A Class B:AB: A
{ {
Public void show (show )() Public void display ( )()
{ {
Console. WriteLine(WriteLine (“am show”); Console. WriteLine(WriteLine (“am display
} from b”);
} }
}
Class program
{
Static void main (string [ ][] args)
{
A a=new A
[Link]();
B b = new Bnew B
[Link]();
[Link]();
}
}
ii. Multilevel:
Here parent having child & child become again parent.
Example:
Class A Class B
{ {
Public void show (show )() Public void display ( )()
{ {
Console. WriteLine(WriteLine (“am show”); Console. WriteLine(WriteLine (“am display
}} from b”);
} }
Class C:BC: B
{
}
iii. Hierarchical:
One parent having multiple child classes.
Example:
Class bank Class SBI:bank
{ {
Public void timings ( )()
{ }
Console. WriteLine(WriteLine (“9 to 10”); Class HDFC:bank
} {
Public void interest rate ( )() }
{ Class ICICI:bank
Console .WriteLineConsole. WriteLine (“2 {
rps “); }
}
parent
single
child
hierarchialhier
archical
child child child child
v. Multiple inheritance:
It is a concept one child class having more than one parent is known as multiple inheritance.
In c# multiple inheritance is not possible because when two parents having same method name
then confusion to get the properties to the child class.
Here ambiguity (confusion) error occurs.
Example:
Class A Class B
{ {
Void show ( )() Void show (show )()
{ {
Console. WriteLine (“am show Console. WriteLine(WriteLine
from A”); (“am show from B”);
} } }
}
Class C: A, B
{
}
(or)
C = new C
[Link];
By using interfaces, we can achieve multiple inheritance indirectly.
Interest calculator
Class finding
{
Public void interest findfinds (int amt ,amt, int months ,months, int rateint rate)
{
Int interest amtinterest amt=(Amt*months*rate) / 100;
Console. WriteLine(WriteLine (“interest amt=”+=” +interest amt);
}
Public void paypays amt(amt (int P, intT ,intintT, int R)
{
Int total amt=P+( P* T*R) R) / 100 )100);
Console. WriteLine (“total pay=”+=” + total amt);
}}
This keyword:
Used to refer the current class instance variable.
When we have local variable name & instance variable name isname is samesame, we can use
this keyword.
Example:
class keyword
{
int i = 10;
public void show ( )()
{
int i = 20;
Console. WriteLine(i);
Console. WriteLine(this.i);
}
public void display( )display ()
{
Console. WriteLine(i);
}
}
5.[6.] Aggregation:
Aggregation is a process in which onewhich one class defines another class has an entity
reference .reference.
It is another way to reuse the class .class.
It represents has a relationship.
Example:
public class address public class student
{ {
public string city; public int id;
public string state; public string name;
public address(address (string address add ;add;
city, string state)
{ public student ( int(int id, string
[Link] = city; name, string address)
[Link] = state; {
} [Link] = id;
[Link] = name;
[Link] = add;
}
public void display( )display ()
{
Console.
WriteLine(WriteLine (id+"
"+name+" "+[Link]+"
"+[Link]. state);
}
class Program
{
static void Main(Main (string[string [] args)
{
{
address add = new address(address ("ngl", "ts");
student stu = new student(student ("Ramya", add);
[Link]();
}
}
6.[7.] Polymorphism:
It is a Greek word poly means many morphisms means form .form. it is a concept one can behave in
different forms. They are 2 types of polymorphisms.
A. Static polymorphism:
It is a compile timecompile time polymorphism & it can achieve by method by overloading.
a. Overloading:
When a class contain multiple methods with same name & different parameters.
Example:
class addition
{
public void sum(sum (int a, int b)
{
Console. WriteLine(WriteLine (a + b);
}
public void sum(sum (int a, int b, int c)
{
Console. WriteLine(WriteLine (a + b + c);
}
}
Base keyword:
It is used to refer the immediate parent class properties (method & variable). When we have
parent & child having same variable name then we van use base keyword.
Example:
Class A Class B:AB: A
{ {
Public void show () Public void show ( )()
{ {
Console. WriteLine (“am show from A”); Console. WriteLine (“am show from B”);
} }
} Public void display( )display ()
{
Show ( )();
Display( )Display ();
}
}
static void Main(Main (string[string [] args)
{
B b = new B
[Link]();
}
7.[8.] Abstraction:
It is process of hiding the internal details & showing the external features.
To achieve abstraction in C# we have two ways
Abstract class
Interface
i. Abstract class:
It is a class which is declared by using the abstract both abstract & non abstract methods
We cannot create direct object to this abstract class.
We can create object by using their child class constructor
By using abstract class, we cannot achieve 100%.
[ii.] Abstract method :method:
It is a method which is declared by using abstract keyword & this method has no body.
It can be declared inside the abstract class only.
Its implementation must be provided by child classes.
By using abstract
Example:
8.[9.] Interface:
It is a blueprint of a class in c#.
It is like abstract class because all the methods which are declared inside the interface are abstract methods.
It cannot have method body.
We cannot create direct object to interface.
By using child class constructor, we can create.
We can achieve 100% abstraction.
We can achieve multiple inheritance by interface.
Note:
Interface methods are public & abstract by default .default. no need to use public & abstract keywords
explicitly.
Example:
interface animal1 class dog :dog: animal1
{ {
void info(info (); public void info(info ()
void name(name (); {
void sound(sound (); Console. WriteLine(WriteLine ("welcome to
animal info");
} }
public void name(name ()
{
Console. WriteLine("name:dog");
}
public void sound(sound ()
{
Console. WriteLine(WriteLine ("sound:
bow");
}
class cat:animalcat: animal1 static void Main(Main (string[string [] args)
{ {
public void info(info ()
{
Console. WriteLine(WriteLine ("welcome to animal1 a1 = new dog(dog ();
animal info"); [Link]([Link] ();
} [Link]([Link] ();
public voidpublic void name () a1.sound1. (sound ();
{ animal1 a2 = new cat(cat ();
Console. WriteLine(WriteLine ("name: [Link]([Link] ();
cat"); [Link]([Link] ();
a2.sound2. (sound ();
}
public voidpublic void sound(sound () }
{
Console. WriteLine(WriteLine }
("sound :sound: meow");
}
}
Static method:
A static method is a method that belongs to the class itself, not to any specific instance of the class.
We can call static method without creating an object of the class, it means we call it by using class name.
We can’t override the static method.
Example:
class A Class program
{ static void Main(Main (string[string [] args)
public static void show(show () {
{ [Link]();
Console. WriteLine(WriteLine ("am show"); A.a=new A(A ();
} [Link]();
public void display(display () }
{
Console. WriteLine(WriteLine ("am
display");
}
STRING
It is an object of [Link] class that represent sequence of character.
We can perform many operations on strings such as concatenation, comparison, search, replacing, trim,
sorting etc.
String vs string:
In c# string is a keyword which is an alias for [Link] class.
Both string & String are same
Example:
class A
{
static void Main(Main (string[string [] args)
{
string s = "hello";
char[char [] ch = { 'r', 'a', 'm', 'y', 'a' };
string ss= new string(ch);
Console. WriteLine(s);
Console. WriteLine(ss);
}
}
String stores sequence in index based.
IsNull or empty:
It is used to initiate that the specified string is null or empty.
String declaration: Searching:
String sString s=”Ramya=” Ramya” String sString s= “Ramya”;
CwlConsole. WriteLine(s[1]);
Length property: Concatenation:
It is used to find the length of the string. Combining the two strings.
Example: Example:
String s= “Ramya”; String s1=”hello=” hello”;
CwlConsole. WriteLine([Link]); String s2=”Ramya=” Ramya”;
String s3=s1+s2
CwlConsole. WriteLine(s3);
Toupper( ) ; & Tolower( ); : Equals:
To convert the whole string into lower we use This method is used to compare the two strings equal
Tolower method. or [Link] returns Boolean values.
To convert the whole string into upper we use Example:
Toupper method. String s1=”hello=” hello”;
Example: String s2=”HELLO=” HELLO”;
String s=”Ramya=” Ramya”; CwlConsole. WriteLine(WriteLine (s1.equals1.
CwlConsole. WriteLine(WriteLine equals (s2)); //false
([Link]( ) );
Replace: Remove:
It is used to replace the current string to new It is used to remove the character from specified
string. index position.
Example: Example:
String s=”hello=” hello java”; String sString s=”hello=” hello java”;
String ss=[Link](“java”,”.net,” .net”); CwlConsole. WriteLine(WriteLine (remove(remove
CwlConsole. WriteLine(ss); (2));
Swapping of string (using 3rd variable) : Swapping of string ( without using 3rd variable) :
String a=”java”; String a=”java”;
String b=”.net=” .net”; String b=”python=” python”;
String c; a=a+b; //javapython
c=a; //c=java b=[Link](0,([Link])); //java
a=b; //a=.net a=[Link](b. Length); //python
b=c; //b=java CwlConsole. WriteLine(a);
CwlConsole. WriteLine(a); CwlConsole. WriteLine(b);
CwlConsole. WriteLine(b);
Cuncate: Trim:
It is used to concatenate two specified strings. This method is used to remove the starting & ending
Ex: spaces of the string.
String a=”hello=” hello”; Ex:
String b=”c-sharp”; String s=”Ramya=” Ramya”;
String c=” “; String ss=[Link]( );
CwlConsole. WriteLine([Link](a,b)); CwlConsole. WriteLine([Link]);
CwlConsole. WriteLine([Link]);
NAMESPACE IN C#
It is a folder.
Namespace is a keyword which is used to declare a scope that contains a set of related objects.
We can use namespace to organize the code elements & to create unique types.
Syntax:
Namespace keyword namespacekeyword namespace name
{
//it contains class & method
}
They are two types of namespaces
1. User defined namespace (UDN)
2. Pre-defined namespace
EXCEPTION HANDLING
Exception:
It is an error when error coming at runtime, those errors are called runtime error. Runtime errors are known
as exceptions.
Types of errors:
There are two types of errors:
a. Compile error
b. Runtime error
int[] a = { 1, 2, 3 };
Console. WriteLine(a[5]); runtime error (index out of range)
}
}
Exception:
It is a class in c# . this is responsible for abnormal program termination when runtime error occur while
running the program.
Note: exception & runtime errors are same. Exceptions are classes that are responsible for the abnormal
program termination.
Common exceptions in c#:
1. Indexoutofrange exception
2. Nullreference exception
3. Format exception
4. Dividebyzero exception
5. Filenotfound exception
6. SQL exception
Handling exception:
For exception handling in c# we have 4 keywords
Try
Catch blocks
Finally
Throw
Ex:
class exp
{
static void Main(Main (string[string [] args)
{
Console. WriteLine("welcome");
string[string [] subject = { "{“biology", "maths", "social" }”};
Console. WriteLine(WriteLine ("enter code");
int code = Convert.ToInt32([Link]());
try
{
Console. WriteLine(WriteLine ("subject selected=" + subject[code]);
}
catch (Exception e)
{
Console. WriteLine(e); (or) or) cwlConsole. WriteLine([Link]);
}
Console. WriteLine(WriteLine ("page close"); } }
Ex: finally
class exp
{
static void Main(string[string [] args)
{
Console. WriteLine(WriteLine ("hai select subject science=0 ,0, maths=1, social=2");
Console. WriteLine(WriteLine ("enter code");
string[string [] sub = { "{“science", "maths", "social" }”};
int code=Convert.ToInt32([Link]());
try
{
Console. WriteLine(WriteLine ("your name is " + sub[code]);
}
catch (Exception e)
{
Console. WriteLine([Link]);
}
finally
{
Console. WriteLine(WriteLine ("exception handled");
}
Console. WriteLine(WriteLine ("page close");
}
Try: it is a block of code which is used to place the code that may throw exception.
Catch: it is a block code which is used to handle the exception. Catch block must be preceded by try block.
Finally: it is a block of code which is used to print a message after exception handling which is executed
whether exception is handled or not. It must be preceded by try or catch block.
Syntax:
Try
{
}
Catch (exception e)
{
}
Finally
{
}
Throw keyword:
a. User defined exception:
By using throw keyword, we can create user defined exception.
To do this we need to inherit exception class.
Ex:.Ex:
Public class invalidage : exception Class test
{ {
Public invalidage(String message): base Public static void invalidage(int age)
(message) {
{ If (age <18)
} {
} Throw new invalidage (“your age is lessthan 18”);
}
Else
{
CwlConsole. WriteLine(WriteLine (“you are
eligible”); } }
ii. Hash table: it represents a collection of key value pairs that are organized based on the hash
code of the key. To retrieve the value, we can access by the key.
Ex:
[a.] static void Main(Main (string[string a.[b.]
[] args) static void Main(Main (string[string [] args)
{ {
Hashtable ht = new Hashtable ht = new Hashtable();
Hashtable(); [Link]("name", "Ramya");
[Link](1, "Ramya"); [Link]("id",4);
[Link](4, "pranaya"); [Link](5, 8);
[Link](5, "Manasa"); Console. WriteLine(ht("name"));
}
Console. WriteLine(ht(4));
}
iii. Queue: it represents fifo(first in first out ) collection of objects. It is used when you need a need
first in first out access.
Ex:
static void Main(Main (string[string [] args)
{
Queue q = new Queue(Queue ();
[Link]("Ramya");
[Link]("pranya");
[Link]("akki");
Console. WriteLine([Link]);
Console. WriteLine([Link]()`);
}
[iv.] Stack: it is a linear data structure. It represents lifo (last in first out )out) pattern for input / output.
Pop-delete
Ex:
static void Main(Main (string[string [] args)
{
Stack s = new Stack(Stack ();
[Link]("Ramya");
[Link]("pranya");
[Link]("akki");
C # GENERICS# GENERICS
They are namespace in collections. The [Link] namespace.
It contains different pre-defined classes.
These collections are type safe because they are generic means only those items that are type compatible
with type of collection can be stored.
Classes in [Link]
List Sorted set
Stack Dictionary
Queue Sorted dictionary
Linked list Sorted list
Hashset
i. List <T>: it is a collection of strongly typed objects that can be accessed by index & it contains
different types of methods.
It is the generic version of ArrayList.
It can accept duplicate.
Note: in case of a generic collection the type of values we want to store under the collections
need not to be pre-defined types only like int, float, string, etc. but it can also be some user
defined types also.
Ex:
static void Main(Main (string[string [] args)
{
List<int> l1 = new List<int>(> ();
List<string> l2 = new List<string>(> ();
l1.Add1. (Add (1);
l1.Add1. (Add (2);
l2.Add2. Add("Ramya");
l2.Add2. Add("pranaya");
ii. Hash set: Hashset class is used to store remove view element.
it does not store duplicate elements.
It is suggested to use if you have to store only unique elements.
It is found in the [Link] namespace.
Ex:
static void Main(string[string [] args)
{
HashSet<string> set = new HashSet<string>();
[Link]("ramya");
[Link]("pranaya");
[Link]("manasa");
[Link]([Link]); //3
[Link]("ramya");
[Link]([Link]("ramya")); //false
}
iii. Dictionary: dictionary class stores the elements in form of key value pairs.
Dictionary is similar to the non-generic hash table class.
The difference is while creating dictionary object we need to specify that both key and value
types.
Ex:
static void Main(string[string [] args)
{
Dictionary<int,string>dt= new Dictionary<int,string>();
[Link](1, "ramya");
[Link](2, "akki");
[Link](3, "mansa");
// to retieve value we can access by key
[Link](dt[1]); ); //ramya
[Link]([Link]);
}
To get total data
Dictionary<int,string>dt= new Dictionary<int,string>();
[Link](1, "ramya");
[Link](2, "akki");
[Link](3, "mansa");
for each(each (key value pair <int,string> kvp in dt)
{
[Link]([Link]+” “+ [Link]);
iv. Linked list: it is a linear data structure which stores element int the non-contigous location.
This class was coming from the system.
It is a dynamic collectionsdynamic collection which grows according to the need of our program.
Syntax:
Linked list< type> name=new <linkedlist<type>(> ();
Ex:
LinkedList<string> name = new LinkedList<string>(> ();
[Link]("ramya");
[Link]("parnaya");
[Link]("mansa");
It is a class in system. Collections. Generic namespace .namespace. it represents lifo (last in first out). It is
used to when we need last in first out access to icons .icons.
Syntax:
Stack< type> name=new stack<type>( )> ();
Example:
Downloading songs, books arrange
Queue:
It is a class in [Link] it represents first in - first out (fifo) itfifo) it is used to when we
need to first in first out.
Syntax:
Queue<type> array name = new queue<type>( )> ();
Example:
Data entry
DELEGATES
It is used to represent a method. They are also known as function pointers
There are 2 types of delegates available in c#.
Single cast delegate
Multi cast delegate
a. Single cast delegate:
A delegate that is used to represent only one method is known a single cast delegate.
Syntax:
Delegate keyword returntype delegatereturntype delegate name ( (parameter)
Example:
By using static method Non static method
b. Multi cast
A delegate that is used to represent more than one method is known as multi cast delegate.
Example:
By using static method By using non static method
MULTI THREADING
}
else if (i == 3)
{
Console. WriteLine(WriteLine ("wait for 3seconds");
}
else if (i == 5)
{
Console. WriteLine(WriteLine ("your account is blocked");
}
else
{
Console. WriteLine(WriteLine ("try again");
}
}
Example:
public static void tvoid t1()
{
for (int i = 0;i0; i<=10; i++)
{
Console. WriteLine("t1="+i);
}
}
public static void t2()
{
for (int i = 0; i <= 10; i++)
{
Console. WriteLine(WriteLine ("t2=" + i);
}
}
public static void t3()
{
for (int i = 0; i <= 10; i++)
{
Console. WriteLine(WriteLine ("t3=" + i);
}
}
[Link]();
[Link]();
[Link]();
}
}
Current thread:
static void Main(Main (string[string [] args)
{
Thread t = [Link];
[Link] = "main start";
Console. WriteLine([Link]);
[Link]();
[Link]();
[Link]();
}
FILE HANDLING
File: a file isfile is a collection of data stored on a desk with a specific name, extension and directory path.
When you open file using c# for reading and writing process. It becomes stream.
Stream: a stream is a sequence of bytes travelling from source to a destination over a communication path.
They are 2 main streams
Input stream
Output stream
a. Input stream: this stream is used to read data from a file which is known as read operation.
b. Output stream: this stream is used to write data into a file which is known as write operation.
File handling:
File handling in c# refers to various operations that we can perform on a file such as creating a file ,file,
reading data from file, writing data into file.
In c# we have a file class, file stream ,stream, etc which are coming from [Link]
Ex:
internal class Program String path = "C:\\Users\\manaf\\Desktop\\
{ [Link]";
static void Main(Main (string[string [] args)
{ FileStream fs = new FileStream(path,
String path = "C:\\Users\\manaf\\Desktop\\ [Link]);
[Link]";
String name = "surya";
FileStream fs = new FileStream(path,
[Link]); Char[Char [] ch = [Link]();
int i=0;
while ((i=[Link]()) !)!= -1) for(for (int i=0;i0; i<[Link];i++)
{ {
char c = (char)i; char c = ch[i];
[Link](c); byte b = (byte)c;
} [Link](b);
}
StreamReader sr = new StreamReader(fs);
[Link](sr);
int i = 0;
while ((i=[Link]())!= -1)
{
char chr = (char)[Link]();
[Link](chr);
}
streamwriter:
stream writer is a class it is used to write character to a stream in specific loading
it inherits text writer class
it provides write ana writeline methods to provide write data into a file.
Syntax:
Stream stringStream pathstring path=” =” .txt”;
Ex:
Filestream fs= new filestream (path,filemode open on create )create);
Streamwriter sw=new streamwriter (fs);
Sw (“hai”);
StreamReader:
StreamReader is a class it is used to read string data from the stream.
It inherits text reader class.
It provideprovides read and readline methods to read data from the stream.
Assemblies:
An assembly in the .NET [Link] is a file that contains the code ana resources for a program to run.
Assemblies can refer DLL(DLL (dynamic link library)arelibrary) are exe(exe (executable file).