0% found this document useful (0 votes)
3 views50 pages

C#_notes

.NET is a Microsoft-developed framework that supports over 30 programming languages, with C# being the most popular. It allows for the development of various applications, including desktop, web, and mobile apps, using a three-layer architecture consisting of presentation, business, and database layers. C# is a high-level, platform-independent language with features such as object-oriented programming and a rich library, making it suitable for a wide range of applications.

Uploaded by

Bob Marley
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views50 pages

C#_notes

.NET is a Microsoft-developed framework that supports over 30 programming languages, with C# being the most popular. It allows for the development of various applications, including desktop, web, and mobile apps, using a three-layer architecture consisting of presentation, business, and database layers. C# is a high-level, platform-independent language with features such as object-oriented programming and a rich library, making it suitable for a wide range of applications.

Uploaded by

Bob Marley
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

C#

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.

Application layers with .net


To develop an application there are 3 layers.

Presentation layer - HTML, CSS, JAVASCRIPT.


[Link]
Business layer - C#
[Link]
Database layer - SQL server
Why C #
 C# is a high level and platform independent language.
 It was extension of C & C++.
 It was developed by Microsoft.
 Some other features.
 C# is similar to other programming languages like java.

Courses in DOT NET


1. Programming language- C#.
2. UI technologies-HTML, CSS, JAVASCRIPT.
3. Database- SQL server.
4. Server technologies- [Link], [Link]
5. Framework-MVC.
6. API- web API.

C# introduction with history


 Ander’s Hejlsberg is known as founder of c#.
 In the year of 2002 Cc# 1.0 version was released with .net framework.
 Currently in market 12.0 version was recently released.
C # uses
I. Desktop app.
II. Web app
III. Mobile app.
IV. Database app
V. Websites
VI. Web services.
VII. Gaming app.
VIII. VR APP.
C # features
1. Simple
2. Platform independent
3. Language independent
4. Object oriented
5. Component oriented
6. Updatable language
7. Rich library
8. Robust
9. Secured
10. Fast
C # architecture
Source code -CS

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)

[Link] NAME SIZE RANGE


1 Bool 1 bit True/false
2 Char 2 bytes (A-Z), (a-z), special characters
3 Int 4 bytes -2147483648 to +2147483648
4 Long 8 bytes -263 to 265
5 Float 4 bytes 6 decimal digits
6 Double 8 bytes 12 decimal digits
7 String 2 bytes per char Sequence of character

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.

Char to long example:


static void Main(Main (string[string [] args)
{
char grade = 'h';
long points;
points = grade;

Console. WriteLine(points) }

Explicit typecasting example:


Long to char example:
static void Main(string[] args) {
long points = 500;
char grade;
grade = (char)points;

Console. WriteLine(grade);}

Int to char example: Double to long


static void Main (string [] args) static void Main (string [] args)
{ {
int num = 120; double num = 45.5412442;
char grade; long point;
grade = (char)num; point = (long)num;

Console. WriteLine(grade); } Console. WriteLine(point); }

Type conversion methods


Type conversion is also done by using conversion method.
This method is converting from convert class.
String = [Link]();
Int =Conevrt.ToInt32()
Long = Convert.ToInt64()
Char =[Link]()
Double = [Link]()

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

Control flow statements

control flow statements

conditional looping jumping

if while break

if else do while continue

else if for return

nested if nested for

switch for each


[A.] CONDITIONAL :

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

A.[B.] LOOPING STATEMENTS


These statements are used to execute the statement multiple times until the condition satisfies.
Looping is divided into 5 types
1. While loop: entry control loop
It is a looping statement execute the statement multiple times until condition break.
Here condition will first check before executing the statement.
Syntax:
While (condition)
{

}
Example:

Print sentence 10 times Print 1-100 even numbers


static void Main(Main (string[string [] args) {
{ Console. WriteLine ("enter a number");
Console. WriteLine ("number of times"); int a =
int n = Convert.ToInt32([Link]()); Convert.ToInt32([Link]());
while (n <= 10) while (a <= 100)
{ {
Console. WriteLine ("welcome to the if (a % 2 == 0)
class"); {
Console. WriteLine(a);
n++; }
} a++;
} }

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]());

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


{
if (i % 2 == 0)
{
Console. WriteLine(i);
}
}
}
Print table: Print sum of natural numbers:
static void Main (string [] args) static void Main (string [] args)
{ {
Console. WriteLine ("enter a number"); Console. WriteLine ("enter a number");
int n = int n =
Convert.ToInt32([Link]()); Convert.ToInt32([Link]());
int m; int sum = 0;
for (int i = 1; i <= n; i++)
for (int i=1; i<=10; i++) {
{ sum = sum + i;
m = n * i;
Console. WriteLine(n+"*"+i+"="+m); }
} Console. WriteLine(sum);
} }

Print Factorial number: Print Fibonacci number:


static void Main (string [] args) static void Main (string [] args)
{ {
Console. WriteLine ("enter a number"); int a = 0, b = 1;
int n = Convert.ToInt32([Link]()); Console. WriteLine(a);
int fact = 1; Console. WriteLine(b);

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


{ {
fact = fact * i; int c = a + b;
} if (c == 8) continue;
{ Console. WriteLine(c);
Console. WriteLine(fact); a = b;
b = c;
} }
}
Print prime number: Print Armstrong numbers:
static void Main (string [] args) static void Main (string [] args)
{ Console{Console. WriteLine(WriteLine {
("enter a number"); Console. WriteLine ("enter a number");
int m = int i =
Convert.ToInt32([Link]()); Convert.ToInt32([Link]());
int n=m, count = 0; int n = i, arm = 0, rem;
while (n > 0)
for (int i=1; i<=n; i++) {
{ rem = n % 10;
if (n% i==0) arm = arm + rem * rem * rem;
{ n = n / 10;
count++; } }
} if (i==arm)
if(count==2) {
{ Console. WriteLine ("Armstrong
Console. WriteLine ("prime number"); number");
} }
else
{ else
Console. WriteLine ("not a prime {
number"); Console. WriteLine ("not an
} Armstrong");
}

Print alphabets numbers: Print reverse numbers:


static void Main (string [] args) {
{ Console. WriteLine ("enter a number");
Console. WriteLine ("enter an alphabet"); int n =
char Ch = 'a'; Convert.ToInt32([Link]());
while (Ch <= 'z') int rev = 0, rem;
{
if (Ch == 'd') while (n > 0)
{ {
Console. WriteLine("doctor"); rem = n % 10;
} rev = rev * 10 + rem;
else n = n / 10;
{
Console. WriteLine (Ch); Console. WriteLine(rev);
} }
Ch++; }
}

Print palindrome numbers:


static void Main (string [] args)
{
Console. WriteLine ("enter a
number");
int i =
Convert.ToInt32([Link]());
int n = i, rev = 0, rem;

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

Print pattern: ( * Print pattern: (* * * *


** * *
*** * *
* * * *) * * * *)
static void Main(Main (string[string [] args) static void Main(Main (string[string [] args)
{ {
for (int i = 1; i <= 4; i++) for (int i = 1; i <= 4; i++)
{ {
for (int j = i; j <= 4; j++) for (int j = 1; j <= 4; j++)
{ if (i == 1 || i == 4 || j == 1 || j == 4)
[Link](" "); {
} Console. Write(Write ("*");

for (int k = 1; k <= i; k++) }


{ else
[Link]("*"); {
} Console. Write(Write (" ");
Console. WriteLine(WriteLine (); }
}
} Console. WriteLine(WriteLine ();
}
}

Print pattern: (* * * * * Print pattern: E


*111*
*101* static void Main(Main (string[string [] args)
*111* {
* * * * *) for(for (int i=1; i<=5; i++)
static void Main(Main (string[string [] args) {
{ for(for (int j=1; j<=3; j++)
for(for (int i=1; i<=5; i++) {
{ if(if (i==1||i==3||i==5|| j==1)
for(for (int j=1;j1; j<=5; j++) {
{ Console. Write(Write ("*");
if(i==1||j==1||i==5||j==5) }
{ else
Console. Write(Write ("*"); {
} Console. Write(Write ("");
else if(i==3&&j==3) }
{ }
Console. Write(Write (0); Console. WriteLine(WriteLine ();
} }
else
{
Console. Write(Write ("1");
}
}
Console. WriteLine(WriteLine (); ); }
Print pattern: Z Print pattern: X
static void Main(Main (string[string [] args) static void Main(Main (string[string [] args)
{ {
for (int i = 1; i <= 5; i++) for (int i = 1; i <= 5; i++)
{ {
for (int j = 1; j <= 3; j++) for (int j = 1; j <= 5; j++)
{ {
if (i ==1||i==5||j+I = = 6) if (j+i==6||i==j)
{ {
Console. Write(Write ("*"); Console. Write(Write ("*");
} }
else else
{ {
Console. Write(Write (" "); Console. Write(Write (" ");
} } }
} Console. WriteLine(WriteLine ();
Console. WriteLine(WriteLine ();
} }

[C.] JUMPING STATEMENTS :STATEMENTS:


These are looping statements which are used to alter the execution.
There are 3 jumping statements
 Break
 Continue
 Written

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

a. By using new keyword: b. By literal:


Syntax: Syntax:
Datatype [ ] array name =new datatype Datatype [ ] array name = { value1 ,
[size]; value2 , value3, ………};
Example: Example:
{ {
Static void main (string [ ] args) Static void main (string [ ] args)
{ {
Int [ ] a= new int [4 ] // declaring & adding
// adding values Int [ ] a= {1,2,3,4……….};
a [0] = 1; //getting
a [2] = 2; {
// getting data Console. WriteLine (a [2]);
{ }
Console. WriteLine(a[1]); }
}

Length property in array


In array’s length property is used to find the element size of the array & it returns integer value.
Syntax:
a. Int [] a= {1,2,3,4,5,6,7,8};
Int size = a. length;
Console. WriteLine (size);
(or)
Console. WriteLine (a. length);

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

Find small element in array Reverse of array


int [] a = {10,1,8,4}; Int [] a= {1,2,3};
int small = a [0]; For (int i=a. length-1; i>=0; i++)
for (int i=1; i<a. length; i++) {
{ Console. WriteLine(a[i]);
If (small <a[i]) }
{
Small=a[i];
}
}
Console. WriteLine(small); }

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

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


{
For (int j=0; j<a[i]. length++)
{
Console. WriteLine(a[i][j]);
}
Console. WriteLine (); });}

Array exception:
In array while retrieving data of index value out the declared index then arrayindexoutofrangeexception.
Exception is a runtime error.

Find the duplicate number Sorting of array

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


for (int i=0; i<a. Length; i++) int temp;
{ for (int i=0; i<a. Length; i++)
for (int j=i+1; j<a. Length; j++) {
{ for (int j=i+1; j<a. Length; j++)
if (a[i] == a[j]) {
{ if (a[i] >a[j])
Console. WriteLine(a[j]); {
} } } temp=a[i];
a[i]=a[j];
a[j]=temp;
} }
Foreach (int I in a)
{
Console. WriteLine(a[j]);
}
}
}

OOPS (OBJECT ORIENTED PROGRAMMING LANGUAGE)

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

[4.] Method :Method:


It is a block of code with set of instructions .instructions. they are 2 types of methods
 Non written type:
These methods are did not written any values. We can declare this method by void keyword.
 Written type:
These methods are written values according to writtening data types.
We can declare this method by written keyword.
Syntax:
Public written typewritten methodtype method name ( )()
{

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

App a =a = new appnew app ( )();


[Link] (“Ramya” ,9542102145, “hyd” )”);

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

Instance variable Local variable


Which variable we are declaring inside the class Which variable we are declaring inside class &
& outside the method method
It can access throughout the class It can access only inside the method where we
declare
Assigning variable for instance is optional Assigning value for local variable is most

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

Static void main (string [ ][] args)


Bank b= new bank(bank (500);
[Link] (500);
[Link](700);

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 “ :“: “

Parent / base / super child / derived / sub-class


Class B:A
Class A
{
{

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

iv. Hybrid inheritance:


Combination of any two inheritance is known as hybrid inheritance.

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

Keyword key = new keyword ( )();


Key .Key. show ( )();

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

Addition a= new addition ( )();


[Link](1,2,3);

b. Method over riding:


When parent & child contain same method names & child class over rides the parent class
method & getting its own properties is known as method over riding
Example:
Class A Class B:AB: A
{ {
Public virtual void show ( )() Public override void show ( )()
{ {
Console. WriteLine (“am show A”); Console. WriteLine (“am show B”);
} }
} }
B b= new= new B( )B ();
[Link]( );

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.

Class A class B:AB: A


{ {
Public int i=10; public int i = 20;
} public void display(display ()
{
int i = 30;
Console. WriteLine(i); //
30
Console. WriteLine(this.i); //20
Console. WriteLine(base.i); //10

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:

abstract class animal class dog :dog: animal


{ {
public void info(info () public override void name(name ()
{ {
Console. WriteLine(WriteLine ("welcome to Console. WriteLine("name:dog");
animal info"); }
} public override void sound(sound ()
public abstract void name(name (); {
public abstract void sound(sound (); Console. WriteLine(WriteLine ("sound:
} bow");
}
}
class cat: animal static void Main(Main (string[string [] args)
{ {
public override void name () animal a1 = new dog(dog ();
{ [Link]([Link] ();
Console. WriteLine(WriteLine ("name: [Link]([Link] ();
cat"); a1.sound1. (sound ();
animal a2 = new cat(cat ();
} [Link]([Link] ();
public override void sound(sound () [Link]([Link] ();
{ a2.sound2. (sound ();
Console. WriteLine(WriteLine }
("sound :sound: meow");
}
}

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

vi. Multiple inheritance:


By using interface, we can achieve multiple inheritance.
Example:
Interface A Interface B
{ {
Void show( )show (); Void show( )show ();
} }

Class C: A,BA, B static void Main(Main (string[string [] args)


{ {
Public void show ( ) C .C. c = new Cnew C ();
{ [Link]( );
Console. WriteLine(WriteLine (“am from show”) }
}
}

Static variable & static method:


Static variable:
It is a variable in c # that belongs to a class rather than and instant of the class.
Every static variable is stored on the heap memory.
We can call static variable by class name or when a variable is declared as static by using static keyword
then single copy of a variable is created.
Example:
class A Class program
{ {
public int i = 10; //global variable static void Main (string[string [] args)
public int j = 20; //static variable {
Console. WriteLine(WriteLine (A.j);
public void show(show () //20
{
int k = 30; A a =new A ();
Console. WriteLine(k); //local variable Console. WriteLine(WriteLine
} (a.i); //10
[Link](); //30
}

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]( ) );

I evol ym yrtnouc: Palindrome of string:


static void Main(Main (string[string [] args) static void Main(Main (string[string [] args)
{ {
string s = "i love my country"; string s = "madam";
string rev = " "; string original = Tolower();
string[string [] str=[Link](' '); string rev = " ";
for (int i = 0; i < [Link]; i++) for (int i = original. Length - 1; i >= 0; i--)
{ {
char[char [] ch = str[i].ToCharArray(); rev = rev + original[i];
for (int j = Ch. Length - 1; j >= 0; j--) }
{ if (original. Equals(rev))
rev += ch[j]; {
} Console. WriteLine("palindrome");
rev = rev + " "; }
} else
Console. WriteLine(rev); {
} Console. WriteLine(WriteLine ("not
palindrome");
}
}
ToCharArray: Contains:
This method is used to convert the string into It is used to check the specified string occurs within
array. the string or not.
It returns character array. It returns Boolean values.
Example: Example:
String s=”Ramya=” Ramya”; String s=”Ramya=” Ramya”;
Char [] ch=ToCharArray( ); CwlConsole. WriteLine(contains(“mya”);
CwlConsole. WriteLine( chWriteLine(ch[1]);

Ends with: Start with:


It is used to check whether the string was end with It is used to check whether the string was start with
the specified string or not. the specified string or not.
Example: Example:
String s=”I love my country”; String s=”I love my country”;
CwlConsole. WriteLine([Link](“country”)); CwlConsole. WriteLine(WriteLine ([Link](“I ”));
Indexof: LastIndexof:
It is used to find the index position of specified It is used to find the index position of specified
character. It checks first character. character. It checks last character.
Example: Example:
String s=”hello=” javahello java”; String s=”hello=” javahello java”;
CwlConsole. WriteLine([Link](“l”)); CwlConsole. WriteLine(WriteLine
(LastIndexof(“l”));

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

Substring (int begin) : Split:


This method is used to retrieve a substring from This method is used to split the string to multiple
the current string. strings & it returns string array.
Example: Example:
String sString s=”hello=” hello world”; string s = "i love my country";
String ss=[Link](6); string ss = [Link]('');
CwlConsole. WriteLine(ss); Console. WriteLine([Link]);
Output:
{“I” , “love” , “my”, “country”} //4

Substring (int begin, int count) : Clone:


It retrieves the substring from the current string. It is used to return a reference to this instance of
Example: string
String sString s=”hi=” hi java python”; Ex:
String ss=[Link](3); //java python String s=”Ramya=” Ramya”;
String sss=[Link](3,4); // java String ss=[Link]( ); (or) string
ss=(string)[Link]( );

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

Occurrence of char in string: Reverse of string:


static void Main(Main (string[string [] args) static void Main(Main (string[string [] args)
{ {
string s = "Ramya"; string s = "Ramya";
int a = 0; string rev = " ";
for (int i = 0; i < [Link]; i++) for (int i = [Link] - 1; i >=0; i--)
{ {
if (s[i] == 'a') rev = rev + s[i];
{ }
a++; Console. WriteLine(rev);
} }
}
Console. WriteLine(a);
}

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

1. User defined namespace: defined by user.


2. Pre-defined namespace: Developed by system default (c #) Ex: system
To access the one namespace into another namespace we need to use using keyword.
Syntax:
Using keyword namespacekeyword namespace;
Ex: using system;

ACCESS SPECIFIERS OR MODIFIERS


In c# access modifiers are keywords that are used to specify accessibility of variables & methods in the c#
application.
There are 5 access modifiers in c#
 Public
 Private
 Internal
 Protected internal
 Protected
Note: if you don’t mention any modifier default it is private.
We can’t set class as private & protected, protected internal.
Every access modifier access within the class.
NAME ACCESS
Public it can access globally.
Private It can access only within the class
Protected It can access within class & in derived class.
Internal It can access only in current assembly(namespace)
Protected internal It can access in current assembly & derived classes.

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

a. Compile error: the error that occur in a program during compilation.


This error occurs by writing wrong syntax, spelling mistake, missing double quotes ,quotes, missing
terminators(terminators (;), assigning wrong datatypes to variables ,variables, creating object for
interface & abstract class.
b. Runtime error: the error that occur at the time of program execution are called runtime error.
This errors at runtime due to various reasons like trying to open files, wrong implementation of
logic , calling empty values length etc.
Runtime errors are dangerous because whenever they occur in the program the program terminates
abnormally on the same line & next line code will not execute.
Ex:
class exp
{
static void Main(Main (string[string [] args)
{
string s = Ramya; compile time 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”); } }

static void Main(Main (string[string [] args)


{
Console. WriteLine(WriteLine ("enter age");
int age=Convert.ToInt32([Link]());
validage(age);
}
C # COLLECTIONS
In c# collections represents group of objects.
By the help of collections, we can perform various actions on objects(values) such as storing, updating,
deleting, searching, retrieving, sorting etc.
We can store objects in array’sarrays or collections.
Collection has advantage over array.
Array has size limit but objects stored in collection can grow.
Types of collection:
There are 3 ways to work with collections
 System. Collections(Collections (now deplicated)
 [Link]
 [Link]

1. System. Collections: non generic collections in c# is defined in system. Collection namespace.


It is a general-purpose data structure that works on object reference.
It can handle any type of object ,object, but not in a safe type manner which classes coming from the
system. Collection namespace those classes are known as legacy classes.
System. Collections namespace classes
 Array list
 Hash table
 Queue
 Stack
i. Array list: it is a dynamic array. The size of the array is not fixed. It can increase & decrease at
runtime.
Array Array list
static void Main(Main (string[string [] static void Main(Main
args) (string[string [] args)
{ {
int[int [] a = new int[int [5]; ArrayList a= new
a[a [0] = 1; ArrayList(ArrayList ();
a[a [1] = 2; [Link](1);
a[a [2] = 3; [Link](2);
{ Console. WriteLine([Link]);
Console. //2
WriteLine([Link]); //5 [Link](3);
a[3] = 4; Console. WriteLine([Link]);
Console. //3
WriteLine([Link]); //5 }
}

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

Console. WriteLine([Link]); //3


Console. WriteLine([Link]()); ); //akki
Console. WriteLine([Link]());
}

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

for (int i = 0; i < l2.Count2. Count; i++)


{
Console. WriteLine(WriteLine (l1.Count1. Count);
Console. WriteLine(l1[1]);
l2.Remove2. Remove("Ramya");
Console. WriteLine(l2[i]);
Console. WriteLine(WriteLine (l2.Contains2. Contains("Ramya")); //false
}
}
Array to list:
static void Main(Main (string[string [] args)
{
string[string [] sub = { "{“science", "social", "maths" }”};
List<string> subjects = new List<string>(> ();
for (int i = 0; i < [Link]; i++)
{
subjects. Add(sub[i]);
}
Console. WriteLine(WriteLine (subjects[subjects [2]);
subjects. Remove("science");
Console. WriteLine(WriteLine (subjects. Count); ); //2
subjects. Clear(Clear ();
Console. WriteLine(WriteLine (subjects. Count); ); //0
}
Equals:
static void Main(Main (string[string [] args)
{
List<string> stu = new List<string>();
stu. Add("Ramya");
stu. Add("pranaya");
stu. Add("akki");
for (int i = 0; i < [Link]; i++)
{
if (stu[i].Contains]. Contains("akki"))
{
Console. WriteLine(WriteLine ("akki contains at index position" + i);
}
}
List<string> stu2 = new List<string>(> ();
Console. WriteLine([Link](stu2));
}
List to array:
static void Main(Main (string[string [] args)
{
List<string> stu = new List<string>(> ();
stu. Add("Ramya");
stu. Add("Manasa");
stu. Add("akki");
string[string [] str = [Link]();
Console. WriteLine(WriteLine (str[str [0]);
}

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

foreach(foreach (string s in name)


{
[Link](s);
}
}
Difference between linked list & list
The major difference b/w list & linked list is we can add data in index based by using add method. Coming
to linked list we can add in multiple ways like after ,after, before, first, last.
We can add the data in 4 ways
 Add last
 Add first
 Add before
 Add after
v.[ii.]
[iii.]
[iv.]
[v.]
[vi.]
[vii.]
[viii.]
[ix.]
[x.]
[xi.]
[xii.]
[xiii.]
[xiv.]
[xv.]
[xvi.]
[xvii.]
[xviii.]
[xix.]
[xx.]
[xxi.]
[xxii.]
[xxiii.]
[xxiv.]
[xxv.]
[xxvi.]
[xxvii.]
[xxviii.]
[xxix.]
[xxx.]
[xxxi.]
[xxxii.]
[xxxiii.]
[xxxiv.]
[xxxv.]
[xxxvi.]
[xxxvii.]
[xxxviii.]
[xxxix.]
[xl.]
[xli.]
[xlii.]
[xliii.]
[xliv.]
[xlv.]
[xlvi.]
[xlvii.]
[xlviii.]
[xlix.]
[l.]
[li.]
[lii.]
[liii.]
[liv.]
[lv.]
[lvi.]
iv.
Stack:
Stack:

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

Adding elements into stack


To add elements into stack we need to use push method.
Example:
Stack <string > sub = new stack <string>( )> ();
[Link](“science”);
[Link](“social”);
[Link](“maths”);

Accessing elements from the stack


To access elements from stack we need to use foreach loop
Syntax:
Foreach (var s in sub)
{
Console. WriteLine(s);
}

Removing elements from stack


To remove elements from the stack we have pop method and it can remove top element in the stack and
return the element.
To remove all elements there is a method called clear.
Syntax:
Console. WriteLine ([Link]( )); //maths

Getting top most element from stack


To get the top element from the stack we have peak method and returns the element.
Syntax:
Console. WriteLine ([Link]( ));

Checking weather an element is exist or not


To check element exists or not in stack we use contains [Link] returns Boolean values.
Syntax:
Console. WriteLine ([Link]( “social”));

Copying stack elements to array:


To copy a stack element to array we need to use copy to method.
Syntax:
Copyto(array name , indexname, index)
Example:
String [ ][] s=new string [10];
[Link](s,0);

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

Adding elements into queue


To add elements into queue we need to use Enqueue method.
[Link](“science”);
[Link](“social”);
[Link](“maths”);

Accessing elements from the queue


To access elements from queue we need to use foreach loop
Syntax:
Foreach (var s in sub)
{
Console. WriteLine(s);
}

Removing elements from queue


To remove elements from the queue we have dequeue method and it can remove top element in the queue
and return the element.
To remove all elements there is a method called clear.
Syntax:
Console. WriteLine ([Link]( )); //science

Getting top most element from queue


To get the top element from the queue we have peak method and returns the element.
Syntax:
Console. WriteLine ([Link]( ));

Checking weather an element is exist or not


To check element exists or not in queue we use contains [Link] returns Boolean values.
Syntax:
Console. WriteLine ([Link]( “social”));

Copying queue elements to array:


To copy a queue element to array we need to use copy to method.
Syntax:
Copyto (array name , indexname, index)
Example:
String [ ][] s=new string [10];
[Link](s,0);

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

class demo class demo


{ {
static void show(show (string s) public voidpublic void show(show (string s)
{ {
Console. WriteLine(WriteLine ("am Console. WriteLine(WriteLine ("am
executing"+ s); executing"+ s);
} }
delegate void singleD(string s); delegate void singleD(string s);
static void Main(Main (string[string [] args) static void Main(Main (string[string [] args)
{ {
singleD d = new singleD(show); demo d= new demo(demo ();
d("Ramya"); singleD sd = new singleD([Link]);
} sd("Ramya");
} }
}

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

class mathematics class mathematics


{ {
static void add(add (int i, int j) public void add(add (int i, int j)
{ {
Console. WriteLine(WriteLine ("sum =" + Console. WriteLine(WriteLine ("sum =" +
(i + j)); (i + j));
} }
static void sub(sub (int i, int j) public void sub(sub (int i, int j)
{ {
Console. WriteLine(WriteLine ("sub" + (i Console. WriteLine(WriteLine ("sub" + (i
- j)); - j));
} }
static void multiple(multiple (int i, int j) public void multiple(multiple (int i, int j)
{ {
Console. WriteLine(WriteLine ("multiple" Console. WriteLine(WriteLine ("multiple"
+ (i*j)); + (i*j));
} }
delegate void md (int i, int j); delegate void sum (int i, int j);
static void Main(Main (string[string [] args) static void Main(Main (string[string [] args)
{ {
md m = new md(add); mathematics d = new
m(m (10, 20); mathematics(mathematics ();
sum ad = new sum ([Link]);
md m1=new md(sub); ad(ad (10, 20);
m1(20, 10); sum su = new sum([Link]);
} su(50, 20);
} }
}

MULTI THREADING

It is a process in which multi thread works simultaneously.


It is process to achieve multi-tasking. It saves time because multiple tasks are being executed at a time.
To create multi thread or thread we need to use system. Threading namespace.
Example: threading
static void Main(Main (string[string [] args)
{

string user = "Ramya";


string password = "ramya@123";
{
for (int i = 1; i <= 5; i++)
{

Console. WriteLine(WriteLine ("enter a username");


string un = [Link]();

Console. WriteLine(WriteLine ("enter password");


string ps = [Link]();

if (un == user && ps == password)


{
Console. WriteLine(WriteLine ("login success");
break;

}
else if (i == 3)
{
Console. WriteLine(WriteLine ("wait for 3seconds");

Thread. Sleep(Sleep (3000);

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

static void Main(Main (string[string [] args)


{
Thread ts1 = new Thread(t1);
Thread ts2 = new Thread(t2);
Thread ts3 = new Thread(t3);

[Link]();
[Link]();
[Link]();
}
}
Current thread:
static void Main(Main (string[string [] args)
{
Thread t = [Link];
[Link] = "main start";
Console. WriteLine([Link]);

Thread ts1 = new Thread(t1);


Thread ts2 = new Thread(t2);
Thread ts3 = new Thread(t3);

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

Filestream fs=new filestrea(path, filemode open or create)


While ([Link] ( )!=>l)
{
[Link]([Link]( ));
}
Int I =0;
While ((i=[Link]( ))=!-1)
{
Char c=(char)I;
[Link](c);
}

Streamwriter sw=new streamwriter (fs)


[Link](“surya”);
[Link]();
[Link]( );

streamReader sr= new streamReader(fs);


[Link]([Link]( ));
[Link]( );
[Link]( );

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.

String pathString path=” =” .txt”;


Filestream fs=new filestream (path,filemode , open on create);
StreamReader sr=new streamReader (fs);
String data =[Link]( );
[Link](data);

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).

You might also like