2. Prepared By: Chirag Patil Page 2
ASP.NET
.NET: .NET is a framework
Framework is a something like platform or an environment, where we can create
program or an application such as console, windows, all web based applications.
Architecture of .NETframework:
CLR (Common Language Runtime): It performs memory management, resource
management, threading and program execution. Code managed by CLR is called as managed
code.
CLR converts any .NET programming language source code into Microsoft based
Intermediate Language called MS IL. Then it is converted into executable.
CLS (Common Language Specification): It specifies the reusability of types and
interoperability between languages provided by .NET framework.
3. Prepared By: Chirag Patil Page 3
CTS (Common Type System): It specifies declaring, reusing and managing of type such
as variables, classes, enumeration, functions and structures.
FCL (.NETFramework Class Library): It provides huge amount of libraries to perform
various operations.
C#:
C# is a modern object oriented .NET based programming language developed by Anders,
while developing .NET framework an recognized or approved by ECMA (European Computer
Manufacture Association) and ISO. It is possible to create windows as well as console
applications using C#. It supports all the features of Object Oriented Programming
Structures such as, Encapsulation, Abstraction, Inheritance and Polymorphism.
Basic Concept:
Keywords: There are some special reserved words with special meaning. Int, return, void
Identifier: A word used to identify types.
Operators:
Arithmetic: +, -, /, *, %
Logical: AND (&&), OR (||), NOT (!)
Comparison: <, >, >=, <=, ==, !=
Period: .
Compiler:
It is an utility program that checks syntax error and converts programming language to
machine level language.
Write a c# program to display “Hello”message
class demo
{
public static void Main(string[] args)
{
System.Console.WriteLine("Hello");
}
4. Prepared By: Chirag Patil Page 4
}
Compile → CSC first.cs Execute → first.exe
Class:Class is a collection of data members (properties) and member functions (actions,
methods).
Main:Starting point of execution.
Void:Return type, Void does not return a value.
Static: Static data member and member functions are called without object.
Public: Access specifire, Accessible to everywhere.
WriteLine: To print the message.
Console: Object of systemclass.
Object: Object is a instance of a class or blue print of a class.
System: Class defines various methods to print or to take input from user.
Variables: It is like a container which holds some value according to its data types.
Data types:
Char 2 bytes = 16 bits = 216 = 65536
Int 4 bytes = 32 bits
Float 4 bytes
Double 8 bytes
Long 8 bytes
Byte 1 byte
Boolean 1 bit
String Mutable
Write a c# program to display additionof numbers
class demo
{
public static void Main(string[] args)
5. Prepared By: Chirag Patil Page 5
{
Int a=10, b=20;
System.Console.WriteLine("Addition: "+(a+b));
Console.ReadKey();
}
}
Write a c# program to take input from user
using system;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class program
{
static void Main(string[] args)
{
Int a;
Console.WriteLine("Enter Number:");
a=Convert.ToInt32(Console.ReadLine());
Console.ReadKey();
}
}
}
Conditional Statements:
1. if…..else
2. switch
Write a c# program for if…..elsestatement
class program
{
static void Main(string[] args)
{
Int a=15;
If(a%2==0)
{
Console.WriteLine(a+" is even");
}
6. Prepared By: Chirag Patil Page 6
else
{
Console.WriteLine(a+” is odd”);
}
Console.ReadKey();
}
}
Write a c# program for switchstatement
class program
{
Static void Main(String[] args)
{
int a=5;
switch(a)
{
case 1:
Console.WriteLine("Mon");
break;
case 2:
Console.WriteLine("Wed");
break;
case 3:
Console.WriteLine("Fri");
break;
default:
Console.WriteLine("Sun");
break;
}
Console.ReadKey();
}
}
Loops
While loop:
class program
{
Static void Main(String[] args)
{
int i=1;
while(i<=5)
7. Prepared By: Chirag Patil Page 7
{
Console.WriteLine(i);
i++;
}
Console.ReadKey();
}
}
Write a c# program to findreverse of a number
class Program
{
static void Main(string[] args)
{
int n=123,r=0,a;
while (n > 0)
{
a = n % 10;
r = (r * 10) + a;
n = n / 10;
}
Console.WriteLine(r);
Console.ReadKey();
}
}
Do While loop:
class Program
{
static void Main(string[] args)
{
int i=0;
do
{
Console.WriteLine(i);
i++;
} while (i <= 5);
Console.ReadKey();
}
}
For:
class Program
8. Prepared By: Chirag Patil Page 8
{
static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
}
Nestedfor:
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 3; j++)
{
Console.WriteLine("*");
}
Console.WriteLine("");
}
Console.ReadKey();
}
}
Array:
Array is a collection of similar types of data elements that can occupy continuous memory
allocation.
Array index always start with 0 up to size -1.
Types of array:
1. 1D
2. 2D
3. Multidimensional
4. Jagged dimension
9. Prepared By: Chirag Patil Page 9
1D array:
Declaration: int[]a=new int[];
class Program
{
static void Main(string[] args)
{
int[] a=new int[2];
Console.WriteLine("Enter array elemnets");
for (int i = 0; i < 2; i++)
{
a[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Array Elements:");
for (int i = 0; i < 2; i++)
{
Console.WriteLine(a[i]);
}
Console.ReadKey();
}
}
Write a c# program to create anarray of size 5, take input from user and find
largest element or value from array
class Program
{
static void Main(string[] args)
{
int[] a=new int[5];
int max;
Console.WriteLine("Enter array elemnets");
for (int i = 0; i <= 4; i++)
{
a[i] = Convert.ToInt32(Console.ReadLine());
}
max = a[0];
for (int i = 0; i<= 4; i++)
{
if (a[i] > max)
max = a[i];
}
10. Prepared By: Chirag Patil Page 10
Console.WriteLine("Maximum: "+max);
Console.ReadKey();
}
}
2D array:
Declaration: int[, ] a=new int[2,2];
class Program
{
static void Main(string[] args)
{
int[,] a = new int[2, 2];
Console.WriteLine("Enter 4 array Elements:");
for (int i = 0; i <= 1; i++)
{
for (int j = 0; j <= 1; j++)
{
a[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Array Elements:");
for (int i = 0; i <= 1;i++ )
{
for (int j = 0; j <= 1;j++ )
{
Console.WriteLine(a[i,j]+" ");
}
Console.WriteLine(" ");
}
Console.ReadKey();
}
}
Write a c# program to performmultiplicationof two2D arrays or matrices
class Program
{
static void Main(string[] args)
{
int i, j;
int[,] a = new int[2, 2];
11. Prepared By: Chirag Patil Page 11
Console.WriteLine("Enter elements for first matrix");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
a[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("First matrix is:");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.Write(a[i, j] + "t");
}
Console.WriteLine();
}
int[,] b = new int[2, 2];
Console.WriteLine("Enter elements for second matrix");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
b[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("second matrix is:");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.Write(b[i, j] + "t");
}
Console.WriteLine();
}
Console.WriteLine("Matrix multiplication is:");
int[,] c = new int[2, 2];
for (i = 0; i < 2; i++)
12. Prepared By: Chirag Patil Page 12
{
for (j = 0; j < 2; j++)
{
c[i, j] = 0;
for (int k = 0; k < 2; k++)
{
c[i, j] += a[i, k] * b[k, j];
}
}
}
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.Write(c[i, j] + "t");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
Write a c# program to findtranspose of an array
class Program
{
static void Main(string[] args)
{
int[,] a = new int[2, 2];
Console.WriteLine("Enter 4 array Elements:");
for (int i = 0; i <= 1; i++)
{
for (int j = 0; j <= 1; j++)
{
a[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Transpose of A:");
for (int i = 0; i <= 1;i++ )
13. Prepared By: Chirag Patil Page 13
{
for (int j = 0; j <= 1;j++ )
{
Console.WriteLine(a[j,i]+" ");
}
Console.WriteLine(" ");
}
Console.ReadKey();
}
}
Jagged array:
C# provides a new type of array called jagged array.
Jagged array is basically a array of arrays (single array of multiple arrays).
Declaration: int[][] a=new int[3][];
class Program
{
static void Main(string[] args)
{
int[][] a = new int[3][] { new int[] { 10 }, new int[] { 20, 30 }, new int[] { 40, 50, 60 } };
Console.WriteLine("Array Elements: ");
for (int i = 0; i <= 2; i++)
{
for (int j = 0; j <= i; j++)
{
Console.WriteLine("a["+i+"]["+j+"]:"+a[i][j]);
}
}
Console.ReadKey();
}
}
Type Casting (Conversion):
Conversion from one type to another
It has two types:
1. Implicit 2. Explicit
1. Implicit type conversion performs automatically.
14. Prepared By: Chirag Patil Page 14
2. In Explicit type conversion we have to use some inbuilt functions.
For Ex.:
ToString()
{
Convert.ParseInt
}
Explicit conversion has two types:
i. Boxing: In this conversion, we convert value type variable to reference type. That means
Stack to Heap.
ii. Un-Boxing: In this conversion. we convert reference type variable to value type variable.
That means Heap to Stack.
class Program
{
static void Main(string[] args)
{
int i = 10;
object o = i; //boxing
Console.WriteLine(o);
int j=(int)o; //unboxing
Console.WriteLine(j);
Console.ReadKey();
}
}
Object orientationwithc#:
1. Encapsulation: Wrapping data members (properties) and member functions into a
single unit, a unit is called class and the process is called as encapsulation.
2. Abstraction: Hiding information from outside the world and allow access to only those
that are required. This can be achieved using access specifire provided by C#.
i. Public: Accessible to all.
ii. Private: Cannot accessible outside block.
iii. Protected: Accessible to only child class.
3. Inheritance (Reusability): Acquiring properties from base (parent) class to derived
(child) class.
15. Prepared By: Chirag Patil Page 15
Single, Multilevel, *Multiple (Interface), Hybrid, Hierarchy
4. Polymorphism: poly means many and morphism means forms.
A single thing can be implemented in various different ways is called as polymorphism.
Function overloading, Function overriding, Operator overloading
Abstract classes: Classes those cannot be instantiate (To create object), but can be
inheritant.
Sealedclass: Opposite of abstract class, Classes those can be instantiate, but cannot be
inheritant.
16. Prepared By: Chirag Patil Page 16
class Person
{
string name;
int age;
public void get()
{
Console.WriteLine("Enter name and age: ");
name=Console.ReadLine();
age=Convert.ToInt32(Console.ReadLine());
}
public void show()
{
Console.WriteLine("Name: "+name+" Age: "+age);
}
}
class program
{
static void Main(string[] args)
{
Person p = new Person();
p.get();
p.show();
Console.ReadKey();
}
}
Functionoverloading:
Functions having same name but different types of parameters.
Write a C# program to create aclass shape having two member functions to
find areaof triangle andcircle
class shape
{
public void area(int r)
{
Console.WriteLine("Area of circle: "+Math.PI*r*r);
}
public void area(int b,int h)
{
Console.WriteLine("Area of triangle: "+(0.5*b*h));
17. Prepared By: Chirag Patil Page 17
}
}
class program
{
static void Main(string[] args)
{
shape s = new shape();
s.area(3); //circle
s.area(3, 4); //triangle
Console.ReadKey();
}
}
Inheritance:
Types of Inheritance:
18. Prepared By: Chirag Patil Page 18
C# does not support multiple Inheritance. So it provides a new concept called interface.
1) Single:
class shape
{
public void show()
{
Console.WriteLine("This is base class");
}
}
class circle : shape
{
public void area(int r)
{
Console.WriteLine("Area of a circle: "+Math.PI*r*r);
}
}
class program
{
static void Main(string[] args)
{
circle c = new circle();
c.show();
c.area(4);
Console.ReadKey();
}
}
2) Multilevel:
class student
{
public void show(int id,string name)
{
Console.WriteLine("Id: "+id+" Name: "+name);
}
}
class marks:student
{
protected int m1, m2, m3;
public void get(int a, int b, int c)
19. Prepared By: Chirag Patil Page 19
{
m1 = a;
m2 = b;
m3 = c;
}
}
class result : marks
{
public void display()
{
Console.WriteLine("Total marks: "+(m1+m2+m3));
}
}
class program
{
static void Main(string[] args)
{
result r=new result();
r.show(12,"ABC");
r.get(50,55,60);
r.display();
Console.ReadKey();
}
}
3) Multiple:
Multiple interface is same as class but it contains method declaration or function
declaration. That means body of its function will be implemented by child class.
interface addition
{
void add(int a,int b);
}
interface subtraction
{
void sub(int a, int b);
}
class arithmetic : addition, subtraction
{
public void add(int a, int b)
{
20. Prepared By: Chirag Patil Page 20
Console.WriteLine("Addition: " + (a + b));
}
public void sub(int a, int b)
{
Console.WriteLine("Subtraction: " + (a - b));
}
}
class program
{
static void Main(string[] args)
{
arithmetic a = new arithmetic();
a.add(10,20);
a.sub(10,20);
Console.ReadKey();
}
}
4) Hierarchy:
class shape
{
public void show()
{
Console.WriteLine("This is base class");
}
}
class circle : shape
{
public void area(int r)
{
Console.WriteLine("Area of circle: "+Math.PI*r*r);
}
}
class triangle:shape
{
public void area(int b, int h)
{
Console.WriteLine("Area of triangle: "+0.5*b*h);
}
21. Prepared By: Chirag Patil Page 21
}
class program
{
static void Main(string[] args)
{
circle c = new circle();
triangle t = new triangle();
c.show();
c.area(4);
t.area(2,3);
Console.ReadKey();
}
}
5) Hybrid:
class student
{
public void show(int id,string name)
{
Console.WriteLine("Id: "+id+" Name: "+name);
}
}
class contact:student
{
public void print(string add)
{
Console.WriteLine("Address: "+add);
}
}
class marks:student
{
protected int m1,m2,m3;
public void get(int a, int b,int c)
{
m1 = a;
m2 = b;
m3 = c;
}
}
class result : marks
22. Prepared By: Chirag Patil Page 22
{
public void display()
{
Console.WriteLine("Total: "+(m1+m2+m3));
}
}
class program
{
static void Main(string[] args)
{
result r = new result();
contact c = new contact();
r.show(121, "XYZ");
c.print("Mumbai");
r.get(20,30,40);
r.display();
Console.ReadKey();
}
}
Functionoverriding:
Program 1: class shape
{
public void area()
{
Console.WriteLine("Base class");
}
}
class circle:shape
{
new public void area()
{
Console.WriteLine("Derived class");
}
}
class program
{
static void Main(string[] args)
{
circle c=new circle();
23. Prepared By: Chirag Patil Page 23
c.area();
Console.ReadKey();
}
}
Program 2: class shape
{
public void area()
{
Console.WriteLine("Base class");
}
}
class circle:shape
{
new public void area()
{
Console.WriteLine("Derived class");
}
}
class program
{
static void Main(string[] args)
{
shape s;
s = new circle();
s.area();
s = new shape();
s.area();
Console.ReadKey();
}
}
Operator overloading:
24. Prepared By: Chirag Patil Page 24
Comparison operator must be overloaded in a pair.
While overloading unary operator, it will take 1 parameter of class type. While overloading
binary operator, it will take 2 parameter of class type.
While overloading both unary and binary operators (Excluding comparison operator) must
return a value.
Unary: class unary
{
int a, b;
public void get()
{
Console.WriteLine("Enter two numbers: ");
a = Convert.ToInt32(Console.ReadLine());
b = Convert.ToInt32(Console.ReadLine());
}
public static unary operator ++(unary x)
{
unary u = new unary();
u.a = ++x.a;
u.b = ++x.b;
return u;
}
public void show()
{
Console.WriteLine("a:{0} b:{1}",a,b);
}
}
class program
{
static void Main(string[] args)
25. Prepared By: Chirag Patil Page 25
{
unary u1 = new unary();
u1.get();
++u1;
u1.show();
Console.ReadKey();
}
}
Binary: class binary
{
int a, b;
public void get()
{
Console.WriteLine("Enter two numbers: ");
a = Convert.ToInt32(Console.ReadLine());
b = Convert.ToInt32(Console.ReadLine());
}
public static binary operator +(binary x,binary y)
{
binary u = new binary();
u.a = x.a+y.a;
u.b = x.b+y.b;
return u;
}
public void show()
{
Console.WriteLine("a:{0} b:{1}",a,b);
}
}
class program
{
static void Main(string[] args)
{
binary b1 = new binary();
binary b2 = new binary();
binary b3 = new binary();
b1.get();
b2.get();
b3 = b1 + b2;
b3.show();
26. Prepared By: Chirag Patil Page 26
Console.ReadKey();
}
}
Comparisonoperator overloading:
Comparison operator must be overloaded in a pair.
For example: If you write code for == then you must have to write code for !=.
While overloading comparison operator it must have return type as bool (Boolean) that is
True or False.
class comparision
{
int a;
public void get()
{
Console.WriteLine("Enter number: ");
a = Convert.ToInt32(Console.ReadLine());
}
public static bool operator ==(comparision x,comparision y)
{
if (x.a == y.a)
return true;
else
return false;
}
public static bool operator !=(comparision x,comparision y)
{
if (x.a != y.a)
return true;
else
return false;
}
}
class program
{
static void Main(string[] args)
{
comparision c1 = new comparision();
comparision c2 = new comparision();
c1.get();
27. Prepared By: Chirag Patil Page 27
c2.get();
if (c1 == c2)
Console.WriteLine("Both same");
else if (c1 != c2)
Console.WriteLine("Both different");
Console.ReadKey();
}
}
Abstract class:
abstract class shape
{
public void area()
{
Console.WriteLine("Method");
}
}
class circle : shape
{
}
class program
{
static void Main(string[] args)
{
circle c = new circle();
c.area();
Console.ReadKey();
}
}
Sealedclass:
sealed class shape
{
public void area()
{
Console.WriteLine("Method");
}
}
class program
{
static void Main(string[] args)
28. Prepared By: Chirag Patil Page 28
{
shape c = new shape();
c.area();
Console.ReadKey();
}
}
Constructor:
Constructor is a special type of member function whose name is same as class name.
Must be always declared in public section. It does not have return type.
When object of its class is created constructor get automatically called.
It used to initialized data members of a class.
Types of constructor:
1) Default Constructor: Does not take any parameter.
2) Parameterized Constructor: It take parameter of primitive data types.
3) Copy Constructor: It takes parameter of class type.
class shape
{
int i, j;
public shape()
{
i = 5;
Console.WriteLine("Default: "+i);
}
public shape(int x)
{
i=x;
Console.WriteLine("Parameterized: "+i);
}
public shape(shape s)
{
i = s.i;
Console.WriteLine("Copy: "+i);
}
}
class program
29. Prepared By: Chirag Patil Page 29
{
static void Main(string[] args)
{
shape s1 = new shape();
shape s2 = new shape(10);
shape s3 = new shape(s2);
Console.ReadKey();
}
}
Exceptionhandling:
Exception handling is a mechanism used to handle logical error.
Error: An abnormalities in a program that leads to program failure or we cannot get desired
outputs.
Types of error:
1) Syntax error: Error cause due to wrong programming syntax.
For Ex.: Semicolon after for loop. These errors are handled by compiler itself.
2) Logical error: Error cause due to wrong programmer logic.
For Ex.: Number divided by 0. An exception handling mechanism used to handle such type of
error.
Exception handling mechanism provides try catch block and finally.
You must place your code in try block and it must be catch by catch block.
Program 1: class program
{
static void Main(string[] args)
{
try
{
int a = 10, b = 0;
int x = a / b;
Console.WriteLine(x);
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.WriteLine(ex.Message);
30. Prepared By: Chirag Patil Page 30
Console.WriteLine("Cannot divide by zero");
}
finally
{
Console.WriteLine("Hi...");
}
Console.ReadKey();
}
}
Program 2: class program
{
static void Main(string[] args)
{
try
{
int[] a ={10,20,30,40};
Console.WriteLine(a[7]);
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
}
Throwing our own exception:
class myexception : Exception
{
public myexception()
{
Console.WriteLine("Father age must be greater");
}
}
class program
{
static void Main(string[] args)
{
try
{
31. Prepared By: Chirag Patil Page 31
int fa, sa;
Console.WriteLine("Enter age of Father and Son: ");
fa = Convert.ToInt32(Console.ReadLine());
sa = Convert.ToInt32(Console.ReadLine());
if (fa <= sa)
throw new myexception();
else
Console.WriteLine("Father Age: "+fa+" Son Age: "+sa);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadKey();
}
}
File handling:
File: Data stored on a specific location, Location refer as folder having directory path. C#
provides System.io namespace with multiple classes to work with an external file.
When we are using any file then it is called as stream. Stream is a sequence of collection of
bytes.
System.io namespace contains various classes that held us to perform read and write
operation with an external file.
When we write data to an external file then we have to use output stream and if we want to
read data from file then we have to use input stream.
Classes provided by system.io namespace:
1) DirectoryInfo: Perform operation related to the directory.
2) FileInfo: Perform operation related to the file.
3) StreamWriter: Allows us to write on an external file character by character.
4) StreamReader: Allows us to read an external file character by character.
5) BinaryWriter: Allows us to write an external file in binary form.
6) BinaryReader: Allows us to read an external file in binary form.
32. Prepared By: Chirag Patil Page 32
Write a C# program to write datato an external file character by character
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class program
{
static void Main(string[] args)
{
StreamWriter sw = new StreamWriter("E://saint.txt");
sw.WriteLine("This is first line");
sw.Close();
Console.ReadKey();
}
}
}
Write a C# program to readdata from an external file character by character
class program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader("E://saint.txt");
string str;
while ((str = sr.ReadLine()) != null)
{
Console.WriteLine(str);
}
sr.Close();
Console.ReadKey();
}
}
Write a C# program to write datato an external file character by character
without removing existing data
class program
{
static void Main(string[] args)
33. Prepared By: Chirag Patil Page 33
{
StreamWriter sw = new StreamWriter("E://saint.txt",true);
sw.WriteLine("This is first line");
sw.Close();
Console.ReadKey();
}
}
Write a C# program to retrievedatafromspecific directory or folder
class program
{
static void Main(string[] args)
{
DirectoryInfo mydir = new DirectoryInfo("E:/project1");
FileInfo[] files = mydir.GetFiles();
foreach(FileInfo f in files)
{
Console.WriteLine(f.Name+" "+f.FullName+" "+f.Length);
}
Console.ReadKey();
}
}
Write a C# program to readand write datato an external file inbinary form
class program
{
static void Main(string[] args)
{
BinaryWriter bw;
BinaryReader br;
int id;
string name;
Console.WriteLine("Enter id and name: ");
id = Convert.ToInt32(Console.ReadLine());
name = Console.ReadLine();
try
{
bw = new BinaryWriter(new FileStream("E:/angelos", FileMode.Create));
bw.Write(id);
bw.Write(name);
bw.Close();
34. Prepared By: Chirag Patil Page 34
}
catch(Exception ex)
{
}
try
{
br = new BinaryReader(new FileStream("E:/angelos", FileMode.Open));
id = br.ReadInt32();
Console.WriteLine("Id: "+id);
name = br.ReadString();
Console.WriteLine("Name: "+name);
br.Close();
}
catch (Exception ex)
{
}
Console.ReadKey();
}
}
Thread: Thread means process.
C# supports multithreading programming that means it is possible to run multiple
processes/threads at a same time concurrently or simultaneously.
Thread is a smallest unit in multithreading program. Basically this concept is used in
programming.
Multitasking: this concept is related to operating system. Task is a smallest unit in
multitasking. Multiple tasks are running simultaneously.
35. Prepared By: Chirag Patil Page 35
Program 1: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class mythread
{
static void Main()
{
Thread t = Thread.CurrentThread;
t.Name = "Main Thread";
Console.WriteLine("This is "+t.Name);
Console.ReadKey();
}
}
}
Program 2: class A
{
public void run()
{
Console.WriteLine("Child thread start");
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
Thread.Sleep(5000);
}
Console.WriteLine("Child thread stop");
}
}
class mythread
{
static void Main()
{
A a = new A();
Thread t = Thread.CurrentThread;
t.Name = "Main Thread";
ThreadStart c1 = new ThreadStart(a.run);
Thread ct = new Thread(c1);
36. Prepared By: Chirag Patil Page 36
ct.Start();
Console.WriteLine("This is "+t.Name);
Console.ReadKey();
}
}
Properties: properties are used to access private data member of a class indirectly.
There are two types of property:
1) get- To access value
2) set- To assign value
class A
{
private int age;
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
}
class mythread
{
37. Prepared By: Chirag Patil Page 37
static void Main()
{
A a = new A();
a.Name = "ABC";
a.Age = 22;
Console.WriteLine("Name: "+a.Name+" Age: "+a.Age);
Console.ReadKey();
}
}
Delegate:
Delegate is a reference to a function. This is same as this pointer to function in c++.
Declaration:
Syntax: delegate datatype delegatename(parameters);
Ex: delegate int mydel(int a,int b);
Initializationof delegate:
Syntax: delegatename object = new delegatename(function);
Ex: mydel m = new mydel(a.add);
Program: delegate int mydel(int a,int b);
class A
{
public int add(int a, int b)
{
return a + b;
}
public int sub(int a, int b)
{
return a - b;
}
}
class mythread
{
static void Main()
{
A a = new A();
mydel m = new mydel(a.add);
mydel n = new mydel(a.sub);
38. Prepared By: Chirag Patil Page 38
Console.WriteLine("Addition: " + m(10, 20));
Console.WriteLine("Substraction: " + n(10, 20));
Console.ReadKey();
}
}
Structure:
Collection of different types of data elements. It occupies random memory location to
access data member of a structure. We need to create object of the structure.
Structure is defined using struct keyword.
Program: struct student
{
public int id;
public string name;
}
class mythread
{
static void Main()
{
student s = new student();
Console.WriteLine("Enter Id and Name: ");
s.id = Convert.ToInt32(Console.ReadLine());
s.name = Console.ReadLine();
Console.WriteLine("Id: "+s.id+" Name: "+s.name);
Console.ReadKey();
}
}
Difference betweenclass andstructure:
No. Class Structure
1 Class support inheritance. Structure does not support inheritance.
2 Class support polymorphism. Structure does not support polymorphism.
3 Class is reference type. Structure is value type.
4 Class is stored in Heap. Structure is stored in Stack.
5 By default member of class are private. By default member of structure are public.
Garbage collection:
39. Prepared By: Chirag Patil Page 39
It is mechanism provided by .NET framework to release memory occupied by an object. It is
an automate process that help to reduce the memory and allocate the same memory for
other use.
Destructor is used to release memory occupied by constructor.
There are two ways to release memory:
1) Assign NULL value to an object.
2) Use GC.collect method.
Program: class student
{
public student()
{
Console.WriteLine("Reserved");
}
~student()
{
Console.WriteLine("Free");
}
}
class mythread
{
static void Main()
{
student s = new student();
Console.ReadKey();
}
}
41. Prepared By: Chirag Patil Page 41
Visual Basic PowerPacks:
Pointer, PrintForm, LineShape, OvalShape, RectangleShape & DataRepeater.
Properties usedwithcontrols:
1. Button:
BackColor- To change background color
Anchor- Anchoring (left, right, top, bottom)
BackgroundImage- To set background image
BackgroundImageLayout- To set layout of image (Tile, Center, Stretch, Zoom)
Font- Name, Size, Bold, Italic, Strikeout, Underline
ForeColor- Text color of the text on button
Text- Text displayed on button
Name- Name of the control
Size- Size of the control (Height & Weight)
CausesValidation- True or False
& Many More
2. Textbox:
BackColor, BackgroundImage, Font, ForeColor, Name, CausesValidation
RightToLeft- Position of the text (Yes or No or Inherit)
Multiline- To add multiple lines (True or False)
Enabled- Mode of enabling (True or False)
& Many More
3. MonthCalendar:
MaxDate- To set maximum date
MinDate- To set minimum date
4. NotifyIcon:
BaloonTipIcon- None, Info, Warning & Error
42. Prepared By: Chirag Patil Page 42
BaloonTipText- To give message
BaloonTipTitle- Title of the popup
Icon- Icon of the notifyicon
Text- As a tooltip of notify icon
5. ProgressBar:
Minimum, Maximum, Value
Form:
StartPosition- Starting position of form
WindowsState- Normal or Minimized or Maximized
Icon- Icon of the form
Every control has ToolTip property. When you use ToolTip control you can set ToolTip text
to every control in two ways.
1) Property of a specific Control
2) Using SetToolTip ethod
toolTip1.SetToolTip(Control_Name, "Message");
ComboBox:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int i = comboBox1.SelectedIndex;
if (i == 0)
{
label1.Text= "Fy";
}
else if (i == 1)
{
label1.Text = "Sy";
}
else if (i == 2)
{
label1.Text = "Ty";
}
}
43. Prepared By: Chirag Patil Page 43
ListBox:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int i = listBox1.SelectedIndex;
if (i == 0)
{
label4.Text = "Fy";
}
else if (i == 1)
{
label4.Text = "Sy";
}
else if (i == 2)
{
label4.Text = "Ty";
}
}
CheckBox:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked == true && checkBox2.Checked==true)
{
label1.Text = checkBox1.Text+","+checkBox2.Text;
}
else if (checkBox1.Checked == true)
{
label1.Text = checkBox1.Text;
}
else if (checkBox2.Checked == true)
{
label1.Text = checkBox2.Text;
}
else
{
label1.Text = "";
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
48. Prepared By: Chirag Patil Page 48
richTextBox1.Font = fontDialog1.Font;
}
}
private void button5_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.ForeColor = colorDialog1.Color;
}
}
Print Dialog:
private void button6_Click(object sender, EventArgs e)
{
printDocument1.DocumentName = "My Doc";
printDialog1.AllowSomePages = true;
printDialog1.AllowCurrentPage = true;
if (printDialog1.ShowDialog() == DialogResult.OK)
{
printDocument1.PrinterSettings = printDialog1.PrinterSettings;
printDocument1.Print();
}
}
private void printDocument1_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawString(richTextBox1.Text,richTextBox1.Font,Brushes.Black,new
Rectangle(50,50,e.PageBounds.Width-50,e.PageBounds.Height-50));
}
SQL Database connectivity withc#:
To work with SQL connectivity you must have to use two namespaces such as
System.Data.Sql and System.Data.SqlClient.
SqlConnection: A SqlConnection object represents a unique session to a SQL server data
source. SqlConnection is used together with SqlDataAdapter and SqlCommand to increase
performance when connecting to a Microsoft SQL server database.
SqlCommand: A SqlCommand object allows you to query and send commands to a
database. It has methods that are specialized for different commands.
49. Prepared By: Chirag Patil Page 49
ExecuteReader: The ExecuteReader method returns a SqlDataReader object for viewing
the results of a select query.
ExecuteNonQuery: The ExecuteNonQuery method is use to insert, update and delete
SQL commands.
AddWithValue: This method adds a value to the end of the SQL Parameter Collection.
AddWithValue(“Field Name”,value);
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace MWFCsharp2_3
{
public partial class Form9 : Form
{
public Form9()
{
InitializeComponent();
}
SqlConnection con;
void con2db()
{
con = new SqlConnection(@"Data
Source=.SQLEXPRESS;AttachDbFilename=C:UsersstudentDocumentsVisual Studio
2010ProjectsMWFCsharp2-3MWFCsharp2-3saint.mdf;Integrated Security=True;User
Instance=True");
con.Open();
}
private void btnInsert_Click(object sender, EventArgs e)
{
con2db();
SqlCommand com = new SqlCommand("insert into emp
values(@name,@salary)",con);
51. Prepared By: Chirag Patil Page 51
con2db();
SqlCommand com = new SqlCommand("select * from emp where eid=@id", con);
com.Parameters.AddWithValue("@id", textBox3.Text);
SqlDataReader dr;
dr = com.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
textBox1.Text = dr[1].ToString();
textBox2.Text = dr[2].ToString();
}
else
{
MessageBox.Show("Data Not found");
}
dr.Close();
con.Close();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (textBox3.Text == "" || textBox2.Text=="" || textBox1.Text=="")
{
MessageBox.Show("Must search record first");
}
else
{
con2db();
SqlCommand com = new SqlCommand("delete from emp where eid=@id", con);
com.Parameters.AddWithValue("@id", textBox3.Text);
com.ExecuteNonQuery();
MessageBox.Show("Data Deleted");
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
con.Close();
}
}
}
}
52. Prepared By: Chirag Patil Page 52
ADO.NET
ADO.NET is a technology used to access and manipulate data from any database either
relational or non-relational in connected or disconnected mode. It reduces no. of objects
required to access & manipulate data. It stands for Active Data Object. It is component of
.NET framework.
1) ConnectedMode:
In this mode connection with database or data source is continuously open. Basically, this
mode uses following objects.
1. SqlConnection
2. SqlCommand
3. SqlDataReader
4. DataTable
SqlConnection con;
void con2db()
{
con = new SqlConnection(@"Path of Database File");
con.Open();
}
private void btnshow_Click(object sender, EventArgs e)
{
con2db();
SqlCommand com=new SqlCommand("select * from emp",con);
SqlDataReader dr;
dr = com.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataGridView1.DataSource = dt;
con.Close();
}
2) DisconnectedMode:
This is an important mode in an ADO.NET framework. In this mode it does not required an
open connection. Data is stored on a client side.
53. Prepared By: Chirag Patil Page 53
Objects used in disconnected mode are created in such a way that when connection is
required it will open a connection and whenever all the task with the database is perform it
will automatically closes the connection.
It provides following objects:
1. SqlConnection
2. SqlDataAdapter
3. DataSet
SqlConnection con;
void con2db()
{
con = new SqlConnection(@"Path of Database file");
}
private void btnshow_Click(object sender, EventArgs e)
{
con2db();
SqlDataAdapter da = new SqlDataAdapter("select * from emp",con);
DataSet ds = new DataSet();
da.Fill(ds,"emp");
dataGridView1.DataSource = ds.Tables[0];
con.Close();
}
Linq: Language IntegratedQuery
It is a .NET framework technology developed by Anders and integrated with C# or in .NET in
Visual Studio 2008.
It is a Microsoft query language used to access data from in memory object Databases and
XML.
1. where
2. join
3. sorting ( order by )
4. descending sorting ( order by descending sorting )
1. where:
private void button1_Click(object sender, EventArgs e)
{
54. Prepared By: Chirag Patil Page 54
string[] stations =
{"Saphale","Virar","Vasai","Dadar","Thane","Airoli","Sanpada","Juinagar" };
var sta = from t in stations
where t.Length<=5
select t;
foreach (var i in sta)
{
listBox1.Items.Add(i);
}
}
2. join:
class order
{
public int oid { get; set; }
public string oname { get; set; }
}
class customer
{
public int cid { get; set; }
public string cname { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
List<customer> cust = new List<customer>();
cust.Add(new customer { cid = 1, cname = "ABC" });
cust.Add(new customer { cid = 2, cname = "MNO" });
cust.Add(new customer { cid = 3, cname = "XYZ" });
List<order> ord = new List<order>();
ord.Add(new order { oid = 1, oname = "Pen" });
ord.Add(new order { oid = 1, oname = "Pencil" });
ord.Add(new order { oid = 3, oname = "Eraser" });
var sta = from c in cust
join o in ord
on c.cid equals o.oid
where c.cid == 1
select new { c.cname, o.oname };
foreach(var i in sta)
{
listBox1.Items.Add(i.cname+" "+i.oname);
55. Prepared By: Chirag Patil Page 55
}
}
3. sorting ( order by ):
private void button1_Click(object sender, EventArgs e)
{
string[] stations =
{"Saphale","Virar","Vasai","Dadar","Thane","Airoli","Sanpada","Juinagar" };
var sta = from t in stations
orderby t
select t;
foreach (var i in sta)
{
listBox1.Items.Add(i);
}
}
4. descending sorting ( order by descending sorting )
private void button1_Click(object sender, EventArgs e)
{
string[] stations = { "Saphale", "Virar", "Vasai", "Dadar", "Thane", "Airoli", "Sanpada",
"Juinagar" };
var sta = from t in stations
orderby t descending
select t;
foreach (var i in sta)
{
listBox1.Items.Add(i);
}
}
Linq toSQL:
Linq to SQL is a component of .NET framework that is used to work with SQL database. It is
used to access and manipulate data from SQL database.
It creates ORM (Object Relational Model) layer between SQL database table and object in
your program. This creates automatic class fromwhich we can access data.
private void button1_Click(object sender, EventArgs e)
{
DataClasses1DataContext dc = new DataClasses1DataContext();
var data = from i in dc.emps
56. Prepared By: Chirag Patil Page 56
where i.salary >= 5000 && i.salary <= 13000
select i;
foreach(var d in data)
{
listBox1.Items.Add(d.eid+" "+d.name+" "+d.salary);
}
}
Linq toXML:
using System.Xml.Linq;
private void button1_Click(object sender, EventArgs e)
{
var doc = XDocument.Load(@"E:studyMWFCsharp2-3MWFCsharp2-
3XMLFile1.xml");
var data = from i in doc.Descendants("customer")
where i.Attribute("id").Value=="1"
select i;
foreach (var d in data)
{
listBox1.Items.Add(d);
}
}
Sending mail throughC#:
Google.com → Less secure App (ON/OFF)
using System.Net.Mail;
private void btnSend_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("Sender’s mail address");
mail.To.Add(textBox1.Text);
mail.Subject =textBox2.Text;
mail.Body =textBox3.Text;
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Credentials = new System.Net.NetworkCredential("Sender’s mail address",
"Password");
57. Prepared By: Chirag Patil Page 57
client.Port = 587;
client.EnableSsl = true;
client.Send(mail);
MessageBox.Show(" Mail Sent ");
}
catch (Exception ex)
{
MessageBox.Show("Error : "+ex);
}
}
Report viewer:
Drag and Drop ReportViewer control on a form
Click design a new report
Select your Database, Dataset
Choose your Database
Arrange fields
Choose style →Finish
It will create .rdlc (report definition language client side) file.
It will also create .xsd (XML schema definition language) file which contains your data
source.
private void Form12_Load(object sender, EventArgs e)
{
this.empTableAdapter.Fill(this.saintDataSet.emp);
this.reportViewer1.RefreshReport();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("Please Enter amount");
}
else
{
58. Prepared By: Chirag Patil Page 58
this.empTableAdapter.Fill(this.saintDataSet.emp, decimal.Parse(textBox1.Text));
this.reportViewer1.RefreshReport();
}
}
Deployment:
File menu → Add → New Project → Other Project Types →
Setup & Deployment → Visual Studio Installer → Setup Wizard → OK → Next →
Select primary output from (Project name), contain files, source files, Debug symbols →
Next → Next → Project Summary → Finish
Step 1:
Select user’s Desktop on left panel (Make always create property True) → Right click on
Right panel → Create new shortcut → Go to application’s folder → Select primary Output →
OK
Step 2:
Select User’s Program Menu on left panel (Make always create property True) → Right click
on Right panel → Create new shortcut → Go to application’s folder → Select primary Output
→ OK
Step 3:
Select Application Folder on left panel (Make always create property True) → Right click on
Right panel → Create new shortcut → Go to application’s folder → Select primary Output →
OK
Build menu →Build (SetupFileName)