Anda di halaman 1dari 50

c # - c sharp

features:
1-it is a pure oops based language
2-it is a case sensitive language
3-it derives its syntax's from c-language and oops concept from c++.

variable:
it is a named location created in the system memory to store a value temporarily while
executing a program, and once the program is terminated the value is erased.

program structure in c#

using <<namespace name>>

class <<class name>>


{
public static void Main()
{
statements;
}
}

TO SAVE: filename.cs
TO COMPILE: csc filename.cs
TO EXECUTE: filename

OPERATORS USED IN C#

1-ARITHMETIC
+,-,*,/
2-COMPARISION/RELATIONAL
>,<,>=,<=,<>
3-UNARY
++
--
POST INCREMENT - I++
4-SHORT HAND/COMPOUND
+=,-=,*=,/=
I=I+10
I+=10
5-TERNARY/CONDITIONAL
VARIABLE=CONDITION?TRUE:FALSE
6-BINARY
%
7-SHORT CIRCUIT
&&,||

1
8-LOGICAL OPERATOR
&&,||,!

PROGRAMMING CONSTRUCTIONS IN C#

1-CONDITIONAL
2-SEQUENCE
3-ITERATION

1-CONDITIONAL CONSTRUCTIONS
HERE "if" IS USED.
SYNTAX:
if (condition)
{
statements;
}
----------------------
if(codition)
{
statements;
}
else if (condition)
{
statements;
}
else
{
statements;
}
2-sequence constructions
HERE "switch" CASE
SYNTAX:

switch(expression)
{
case 1:
statements;
break;
case n:
statements;
break;
default:
statements;
break //mandatory

2
}

3-ITERATION CONSTRUCTIONS
A-WHILE
B-DO WHILE
C-FOR
D-FOR EACH
A-WHILE LOOP
SYNTAX:
while(condition)
{
statements;
counter variable;
}
B-DO WHILE
SYNTAX:
do
{
statements;
counter variable;
}while(condition);

C-FOR
SYNTAX:
for(init;conditiion;counter variable)
{
statements;
}

D-for each
syntax:
for each(variable decl in array/collection name)
{
statements;
}

ARRAYS:
A contigious block of memory location having save datatype and name.

SINGLE/DOUBLE DIMENSIONAL

SINGLE DIMENSIONAL
SYNTAX:
datatype[] arrayname = new datatype[size];
int[] arr = new int[5];

3
arr[0]=10 ;
int[] arr = {10,20,30,40,50};

DOUBLE DIMENSIONAL
SYNTAX:
datatype[,] array name=new datatype[row,column];
int[,] arrayname = new int[2,3];

arr[0,0]=10

int[,] arr = {{10,20,30},{40,50,60}};

4
USE OF TERNARY OPERATOR
using System;

class test
{
static void Main()
{
int n;
string res;
Console.Write("Enter a number: ");
n=Int32.Parse(Console.ReadLine());
res=(n%2==0?"Even No":"Odd No");
Console.Write("\n"+res);
}
}

USE OF SIMPLE PROGRAM TO ACCEPT NAME AND AGE

using System;

class demo
{
static void Main()
{
Console.WriteLine("This is my first program");
string nm;
int age;
Console.Write("\n"+"Enter your name and age: ");
nm=Console.ReadLine();
//age=Convert.ToInt32(Console.ReadLine());
age=Int32.Parse(Console.ReadLine());
Console.WriteLine("Your name & age is: {0} - {1}",age,nm);
//Console.WriteLine("Your name is: ",nm,"and age is: "+age);
}
}

using System;

class demo
{
static void Main()
{
int a;
Console.WriteLine("Enter a no: ");
a=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("The value of a is: {0}",a);

5
}
}

PROGRAM ON “IF” CONSTRUCTION

using System;
class ifdemo
{
Stativ Void Main()
{
int n;
Console.WriteLine("enter a no:");
n=Int32.Parse(Console.ReadLine());
if(n%2==0)
{
Console.WriteLine("{0} is an even number",n);
}
else
{
Console.WriteLine("{0} is an odd number",n);
}
}
}

PROGRAM ON “SWITCH” CONSTRUCTION

using System;

class demoswitch
{
static void Main()
{
int day=0;
Console.WriteLine("Enter a weekday serial no[1-7]:");
day=Int32.Parse(Console.ReadLine());

switch(day)
{
case 1:
Console.WriteLine("Monday");
break;
case 7:
Console.WriteLine("Sunday");
break;
default:
Console.WriteLine("Invalid Number Entered");

6
break;
}
}
}

PROGRAM ON “WHILE LOOP” CONSTRUCTION

using System;

class whileprg
{
static void Main()
{
int n=0;
while(n<=10)
{
Console.WriteLine(n);
n++;
}
}
}

PROGRAM ON “DO WHILE” CONSTRUCTION

using System;

class demowhile
{
static void Main()
{
int n=0;
do
{
Console.WriteLine(n);
n++;
}while(n<=10);
}
}

PROGRAM ON ARRAY’s i.e. single dimensional

using System;

class demo
{

7
static void Main()
{
//int[] arr = new int[5];
int[] arr = {10,20,30,40,50};
//Console.WriteLine("Enter 5 no's in an array");

/*for(int i=0;i<5;i++)
{
arr[i]=Convert.ToInt16(Console.ReadLine());
}*/
Console.WriteLine("The contents of array is as follows");
foreach(int i in arr)
{
Console.WriteLine(i);
}
/*for(int i=0;i<5;i++)
{
Console.WriteLine(arr[i]);
}*/
}
}

PROGRAM ON ARRAY’s i.e. double dimensional

using System;

class demo
{
static void Main()
{
//int[,] arr = new int[2,3];
int[,] arr = {{10,20,30},{40,50,60}};
Console.WriteLine("Enter no's in 2x3 array");

/*for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
arr[i,j]=Convert.ToInt16(Console.ReadLine());
}
}*/
Console.WriteLine("The contents of array is as follows");
/*foreach(int i in arr)
{
Console.WriteLine(i);
}*/

8
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
Console.Write(" "+"{0}",arr[i,j]);
}
Console.WriteLine("");
}

}
}

PROGRAM ON ARRAY’s inbuilt functions

using System;

public class demo


{
static void Main()
{
int[] arr = {40,20,50,30,10};
int[] arr1 = new int[5];
int[,] arr2 = new int[2,3];
Console.WriteLine("Contents of array is as follows:");
Console.WriteLine(" ");
for(int i=0;i<5;i++)
{
Console.Write("\t{0}",arr[i]);
}
//USE OF ARRAY.SORT FUNCTION
Console.WriteLine(" ");
Console.WriteLine("Contents of array after sorting");
Array.Sort(arr); //Array.Sort(array name)
Console.WriteLine(" ");
for(int i=0;i<5;i++)
{
Console.Write("\t{0}",arr[i]);
}
Console.WriteLine(" ");

//USE OF ARRAY.REVERSE FUNCTION

Console.WriteLine("Contents of array after user reverse function");


Array.Reverse(arr); //Array.Reverse(array name)
Console.WriteLine(" ");
for(int i=0;i<5;i++)

9
{
Console.Write("\t{0}",arr[i]);
}
Console.WriteLine(" ");

//USE OF ARRAY.LASTINDEXOF FUNCTION

Console.WriteLine("Enter a no to be search into the array: ");


int ser=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Contents of array after user lastindex of function");

int res=Array.LastIndexOf(arr,ser); //Array.Reverse(array name, serach element)


if(res<0)
{
Console.WriteLine("The searched number not found in the array");
}
else
{
Console.WriteLine("The no found at index - {0}",res);
}

//USE OF ARRAY.COPY FUNCTION

Array.Copy(arr,arr1,5); //Array.Copy(source array name, destination array


name, number of pockets to be copy)

Console.WriteLine("Contents of new array after copying from existing array");


Console.WriteLine(" ");
for(int i=0;i<5;i++)
{
Console.Write("\t{0}",arr1[i]);
}
Console.WriteLine(" ");

//USE OF ARRAY.CLEAR FUNCTION

Array.Clear(arr1,0,3); //Array.Clear(source array name, number of pockets


to be deleted)
Console.WriteLine("Contents of new array after using clear function");
Console.WriteLine(" ");
for(int i=0;i<5;i++)
{
Console.Write("\t{0}",arr1[i]);
}
//USE OF length property

10
Console.WriteLine(" ");
int ln = arr1.Length; //length is a property
Console.WriteLine("The length of array after using length function");
Console.WriteLine("The length of array is :{0}",ln);
Console.WriteLine(" ");
Console.WriteLine("The array -ARR- is of {0} dimensional array",arr.Rank);
Console.WriteLine("The array -ARR2- is of {0} dimensional array",arr2.Rank);
Console.WriteLine("The value of index 3 in arr is: {0}",arr.GetValue(3));
Console.WriteLine("The value of index 2 in arr is: {0}",Array.IndexOf(arr1,10));
}
}

PROGRAM ON CALLBY REFERENCE FUNCTION

using System;

class demo
{
static void swap(int x, int y)
{
int z=0;
z=x;
x=y;
y=z;
Console.WriteLine("The value of a and b after swapping is: {0} & {1}",x,y);
}
static void Main()
{
int a,b;
a=10;b=20;
Console.WriteLine("The value of a and b before swapping is: {0} & {1}",a,b);
swap(a,b);
Console.WriteLine("The value of a and b after swapping is: {0} & {1}",a,b);
}
}

using System;

class demo
{
public int a,b;
public void swap(demo d)
{
int z=d.a;
d.a=d.b;
d.b=z;

11
}
}
class test
{
static void Main()
{
demo d = new demo(); //class object created
d.a=10;d.b=20;
Console.WriteLine("The value of a and b before swapping is: {0} & {1}",d.a,d.b);
d.swap(d);
Console.WriteLine("The value of a and b after swapping is: {0} & {1}",d.a,d.b);
}
}

PROGRAM ON USE OF STRUCTURE-1

using System;
struct MyStruct
{
public int x;
public int y;
}
class demo
{
public static void Main()
{
MyStruct ms = new MyStruct();
ms.x = 10;
ms.y = 20;
int sum = ms.x + ms.y;
Console.WriteLine("The sum is {0}",sum);
}
}

PROGRAM ON USE OF STRUCTURE-2

using System;
struct MyStruct
{
public static int x = 25;
public static int y = 50;
}
class demo
{
public static void Main()

12
{
int sum = MyStruct.x + MyStruct.y;
Console.WriteLine("The sum is {0}",sum);
}
}

PROGRAM ON USE OF STRUCTURE –USING FUNCTIONS

using System;
struct MyStruct
{
static int x = 25;
static int y = 50;
public void test1(int i, int j)
{
x = i;y = j;
Console.WriteLine("Value of x and y in test is: {0} - {1}",x,y);
}
public void test2(int i)
{
x = i;y = i;
Console.WriteLine("Value of x and y in test2 is: {0} - {1}",x,y);
}
}
class MyClient
{
public static void Main()
{
MyStruct ms1 = new MyStruct();
MyStruct ms2 = new MyStruct();
ms1.test1(100,200);
ms2.test2(500);
}
}

PROGRAM ON USE OF CLASS CONCEPT

using System;
class democlass
{
public string nm;
public int age;
}
class test
{
static void Main()

13
{
democlass d = new democlass();
Console.WriteLine("Enter u r name & age: ");
d.nm=Console.ReadLine();
d.age=Int32.Parse(Console.ReadLine());
Console.WriteLine("U r name & age is:{0} -{1}",d.nm,d.age);
}
}

PROGRAM ON CONSTRUCTOR

using System;
class democlass
{
public string nm,addr;
public int age,phno;

public democlass(string x, int a)


{
nm=x;
age=a;
}
public democlass(int a,string x)
{
addr=x;
phno=a;
}
~democlass()
{
Console.WriteLine("Destructor");
}

}
class test
{
static void Main()
{
democlass d = new democlass("sam",23);
democlass d1 = new democlass(2554714,"vizag");
Console.WriteLine("U r name,address,age & phno is:{0} - {1} - {2} &
{3}",d.nm,d1.addr,d.age,d1.phno);
}
}

14
PROGRAM ON USE OF PROPERTIES

using System;
class democlass
{
public string nm;
int age;

public int details


{
set //write only property
{age=value;}
get //read only property
{return age;}
}
}
class test
{
static void Main()
{
democlass d = new democlass();
Console.WriteLine("Enter u r name & age: ");
d.nm=Console.ReadLine();
d.details=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("U r name & age is: {0} - {1}",d.nm,d.details);
}
}

PROGRAM ON USE OF POLYMORPHISM/FUNCTION OVERLOADING

using System;
class demo
{
public int sum(int a, int b)
{
return a+b;
}
public string sum(string x, string y)
{
return x+y;
}
public double sum(double a, double b)
{
return a+b;
}

15
public void sum(string nm,string addr,int age)
{
Console.WriteLine("U r name,address and age is: {0} - {1} & {2}",nm,addr,age);
}
}
class test
{
static void Main()
{
demo d = new demo();
Console.WriteLine("{0}",d.sum(10,20));
Console.WriteLine("{0}",d.sum("vizag "," city"));
Console.WriteLine("{0}",d.sum(10.20,30.40));
d.sum("sam","vizag",20);
}
}

PROGRAM ON USE OF INHERITANCE

using System;
class faculty
{
public string nm,addr;
public int age;

public void accept()


{
Console.WriteLine("Enter u r name,age and address: ");
nm=Console.ReadLine();
age=Int32.Parse(Console.ReadLine());
addr=Console.ReadLine();
}
public void display()
{
Console.WriteLine("U r details are as follows: ");
Console.WriteLine("{0}",nm);
Console.WriteLine("{0}",age);
Console.WriteLine("{0}",addr);
}
}
class student:faculty
{
public double mobno;
public void accept1()
{
Console.WriteLine("Enter mobile no: ");

16
mobno=Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Mobile no is: {0}",mobno);
}
}
class test
{
static void Main()
{
student s = new student();
Console.WriteLine("Enter details for faculty");
s.accept();
s.display();
Console.WriteLine("Enter details for student");
s.accept();
s.display();
s.accept1();
}
}

PROGRAM ON OPERATOR OVERLOADING

using System;
public class demo
{
public int hour,min;

public demo(int h, int m)


{
this.hour=h;
this.min=m;
}
public static demo operator+ (demo a, demo b)
{
return new demo(a.hour+b.hour,a.min+b.min);
}
}
class test
{
static void Main()
{
demo d = new demo(10,20);
demo d1 = new demo(10,20);
demo d2 = new demo(d.hour+d1.hour,d.min+d1.min);
Console.WriteLine("The total value is:{0} & {1}",d2.hour,d2.min);
}
}

17
PROGRAM ON USE OF FUNCTION OVERRIDING

using System;

class demo
{
public void display()
{
Console.WriteLine("This is base class's function");
}
}
class derived:demo
{
new public void display()
{
Console.WriteLine("This is derived class's function");
}
}
class test
{
static void Main()
{
derived d = new derived();
d.display();
}
}

PROGRAM ON USE OF FUNCTION OVERRIDING-2

using System;

public class demobase


{
public double inc;
public void incentives(double x)
{
inc=x;
Console.WriteLine("Bydefault value is: {0}",inc);
}
}
public class manager:demobase
{
public new void incentives(double x)
{
x*=.3;
inc=x;

18
Console.WriteLine("Total incentives for manager will {0} amount",inc);
}
}
public class mrkt:demobase
{
public new void incentives(double x)
{
x*=.1;
inc=x;
Console.WriteLine("Total incentives for marketing exe. will {0} amount ",x);
}
}
class test
{
static void Main()
{
manager m = new manager();
mrkt m2 = new mrkt();
Console.WriteLine("Enter amont to calculate incentives for category manager &
marketing executives");
m.inc=Convert.ToInt32(Console.ReadLine());
m.incentives(m.inc);
m2.incentives(m.inc);
Console.WriteLine("Amount for manager is:{0}",m.inc);
Console.WriteLine("Amount for mkt. exe is: {0}",m2.inc);
}
}

PROGRAM ON USE OF ABSTRACTION

using System;
public abstract class democlass
{
public abstract void display(); //abstract method

public void example() //normal method


{
Console.WriteLine("This is the normal function of base class");
}
}
public class derived:democlass
{
public override void display()
{
Console.WriteLine("This is the implementing of abstract method");

19
}
}
class test
{
static void Main()
{
derived d = new derived();
democlass dc = d;//creation of base class object reference of derived type
dc.display();
d.example();
}
}

PROGRAM ON USE OF ABSTRACTION-2

using System;

abstract class bank


{
public abstract void fixdept(int x,double y,int z);
}

class year1:bank
{
public override void fixdept(int x,double y,int z)
{
double ri;
ri=(x*y*z)/100;
Console.WriteLine("Simple interest is: {0}",ri);
}
}
class year2:bank
{
public override void fixdept(int x,double y,int z)
{
double ri;
ri=(x*y*z)/100;
Console.WriteLine("Simple interest is: {0}",ri);
}
}
class test
{
static void Main()
{
year1 y2=new year1();
bank b1 = y2;

20
double r;
int m,p;
Console.WriteLine("Enter duration in months to calculate simple interest [12/24]");
m=Convert.ToInt32(Console.ReadLine());
switch(m)
{
case 12:
Console.WriteLine("Enter loan amount and rate of interest:");
p=Convert.ToInt32(Console.ReadLine());
r=Convert.ToDouble(Console.ReadLine());
//y1.fixdept(p,r,12);
b1.fixdept(p,r,12);
break;
case 24:
Console.WriteLine("Enter loan amount and rate of interest:");
p=Convert.ToInt32(Console.ReadLine());
r=Convert.ToDouble(Console.ReadLine());
//y1.fixdept(p,r,24);
b1.fixdept(p,r,12);
break;
default:
Console.WriteLine("Invalid value entered");
break;
}
}
}

PROGRAM ON USE OF VIRTUAL FUNCTION

using System;
public class baseclass
{
public virtual void display()
{
Console.WriteLine("This is virtual function");
}
}
public class derived:baseclass
{
public override void display()
{
Console.WriteLine("This is override function of derived class");
}
}
public class derived2:baseclass
{

21
public override void display()
{
Console.WriteLine("This is override function of derived2 class");
}
}
class test
{
static void Main()
{
baseclass dc = new baseclass();
derived d = new derived();
derived2 d2 = new derived2();
dc.display();
d.display();
d2.display();
}
}

PROGRAM ON USE OF INTERFACE

//the functions declared in the interface should be implemented in the class

using System;
public interface myinter
{
int sum(int x, int y);
int sub(int x, int y);
}
public class demo : myinter //inheriting the interface
{
public int sum(int x, int y)
{
return x+y;
}
public int sub(int x, int y)
{
return x-y;
}
}
class test
{
static void Main()
{
demo d = new demo();
int a,b;
Console.WriteLine("Enter two no's: ");

22
a=Convert.ToInt16(Console.ReadLine());
b=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("The sum of {0} & {1} is: {2}",a,b,d.sum(a,b));
Console.WriteLine("The subtraction of {0} & {1} is: {2}",a,b,d.sub(a,b));
}
}

PROGRAM ON USE OF INTERFACE AS WELL AS INHERITING CLASS

using System;

public interface myinter


{
int sum(int x, int y);
int sub(int x, int y);
}
public class democlass
{
public void display()
{
Console.WriteLine("This is the normal function of base class");
}
}
public class derived : democlass, myinter
{
public int sum(int x, int y)
{
return x+y;
}

public int sub(int x, int y)


{
return x-y;
}
}
class test
{
static void Main()
{
derived d = new derived();
d.display();
int a,b;
Console.WriteLine("Enter two no's: ");
a=Convert.ToInt16(Console.ReadLine());
b=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("The sum of {0} & {1}is: {2}",a,b,d.sum(a,b));

23
Console.WriteLine("The subtraction of {0} & {1}is: {2}",a,b,d.sub(a,b));
}
}

PROGRAM ON EXPLICIT INTERFACE CONCEPT

using System;
public interface myinter
{
void display();
}
public interface myinter2
{
void display();
}
public class derived:myinter,myinter2
{
void myinter.display()
{
Console.WriteLine("This is display function of first interface");
}
void myinter2.display()
{
Console.WriteLine("This is display function of second interface");
}
}
class test
{
static void Main()
{
derived d = new derived();
myinter m = (myinter) d;
m.display();
myinter2 m2 = (myinter2) d;
m2.display();
}
}

PROGRAM ON NAMESPACE’s

using System;
using trial;
namespace trial
{
public class demo
{

24
public void display()
{
Console.WriteLine("Hello friends");
}
}
namespace trial1
{
public class demo
{
public void display()
{
Console.WriteLine("Hello friends");
}
}
}
}
class test
{
static void Main()
{
//trial.demo d = new trial.demo();
demo d = new demo();
d.display();
trial.trial1.demo d1 = new trial.trial1.demo();
d1.display();
}
}

PROGRAM ON NAMESPACE’s-2

using System;
using trial;
using trial1.trial;
namespace trial
{
public class demo
{
public void display()
{
Console.WriteLine("Hello friends");
}
}
}
namespace trial1
{
public class demo

25
{
public void display()
{
Console.WriteLine("Hello friends");
}
}
public class test
{
public int sum(int x, int y)
{
return x+y;
}
}
namespace trial
{
public class trialclass
{
public int sum(int x, int y)
{
return x+y;
}
}
}
}
class test
{
static void Main()
{
//trial.demo d = new trial.demo();
demo d = new demo();
d.display();
trial1.demo d1 = new trial1.demo();
trial1.test t = new trial1.test();
d1.display();
Console.WriteLine("The sum is: {0}",t.sum(10,20));
//trial1.trial.trialclass tc = new trial1.trial.trialclass();
trialclass tc = new trialclass();
Console.WriteLine("The sum is: {0}",tc.sum(100,200));
}
}

26
PROGRAM ON CREATION OF DLL FILES OR SINGLE FILE ASSEMBLY

namespace ptax
{
public class stax
{
public double servicetax(double x)
{
return (x*12.36)/100;
}
}
}

PROGRAM ON USE OF DLL FILES OR SINGLE FILE ASSEMBLY-2

using System;
using ptax;

class test
{
static void Main()
{
stax t = new stax();
double amt;
Console.WriteLine("Enter an amount: ");
amt=Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Service tax for amount {0} is: {1} and Total Amount is:
{2}",amt,t.servicetax(amt),amt+t.servicetax(amt));
}
}

PROGRAM ON EXCEPTION’s

using System;

class democlass
{
static void Main()
{
try
{
int a,c;
int[] b = new int[1];
Console.WriteLine("Enter 2 numbers: ");
a=Int32.Parse(Console.ReadLine());

27
b[2]=Int32.Parse(Console.ReadLine());
c=a/b[2];
}
//catch (System.Exception e)
catch(System.ArithmeticException e)
{
Console.WriteLine("Result is: {0}",e);
}
catch(System.FormatException e)
{
Console.WriteLine("Result is: {0}",e);
}
catch(System.IndexOutOfRangeException e)
{
Console.WriteLine("Result is: {0}",e);
}
}
}

PROGRAM ON EXCEPTION’s-2

using System;
class democlass
{
static void Main()
{
try
{
int a,b,c;
//int[] b = new int[1];
Console.WriteLine("Enter 2 numbers: ");
a=Int32.Parse(Console.ReadLine());
//b[2]=Int32.Parse(Console.ReadLine());
b=Int32.Parse(Console.ReadLine());
c=a/b;
Console.WriteLine("Result is: {0}",c);
}
catch(System.Exception e)
{
Console.WriteLine(e.StackTrace);
Console.WriteLine(e.Message);
Console.WriteLine(e.ToString());
Console.WriteLine(e.Source);
}
}
}

28
PROGRAM ON EXCEPTION’s – USER DEFINED EXCEPTION USING THROW
KEYWORD

using System;

class democlass
{
static void Main()
{
try
{
string nm;
int age;
Console.WriteLine("Enter u r name & age between [>=20 - <=30]: ");
nm=Console.ReadLine();
age=Int32.Parse(Console.ReadLine());
if((age<20) || (age >30))
throw new System.Exception(age.ToString());
Console.WriteLine("U r name & age is: {0} - {1}",nm,age);
}
catch(System.Exception e)
{
Console.WriteLine("Invalid age entered i.e.{0}",e);
}
}
}

PROGRAM ON DELEGATES-1

using System;
public delegate int demodele(int x, int y);

public class democlass


{
public int sum(int x, int y)
{
return x+y;
}
public int mul(int x, int y)
{
return x*y;
}
}
class test
{

29
static void Main()
{
democlass d = new democlass();
demodele del;
del = new demodele(d.sum);
demodele del1 = new demodele(d.mul);
Console.WriteLine("Enter two no's to addition: ");
int a=Int16.Parse(Console.ReadLine());
int b=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("The sum of {0} & {1} is: {2}",a,b,del(a,b));
Console.WriteLine("The multiplication is: {0}",del1(a,b));
}
}

PROGRAM ON DELEGATES-2

using System;
delegate void dlgSimple();
delegate double Addition();
class Exercise
{
private static void Welcome()
{
Console.WriteLine("Welcome to the Wonderful World of C# Programming!");
}
private static double Plus()
{
double a = 248.66, b = 50.28;
return a + b;
}
static void Main()
{
dlgSimple Announce = new dlgSimple(Welcome);
Addition Add = new Addition(Plus);
Announce();
Console.WriteLine("\n248.66 + 50.28 = {0}", Add());
}
}

PROGRAM ON DELEGATES-3

using System;
public delegate int trial();
class democlass
{

30
int n;
public int sqr1
{
set{ n=value;}
get{return n;}
}
public democlass(int x)
{
sqr1=x;
}
public int sqr()
{
return sqr1*sqr1;
}
public void disp()
{
trial t = new trial(sqr);
Console.WriteLine("The square of {0} is: {1}",sqr1,t());
}
}
class test
{
static void Main()
{
int x;
Console.WriteLine("Enter a number to display square: ");
x=Int32.Parse(Console.ReadLine());
democlass d = new democlass(x);
d.disp();
}
}

PROGRAM ON EVENTS

using System;
delegate void dlgSimple(); //delegate declaration

class Exercise
{
public static event dlgSimple Simply; //event declaration

public static void Welcome()


//normal function
{
Console.WriteLine("Welcome to the Wonderful World of C# Programming!");
}

31
public static void SayHello() //raising of event
{
Simply();
}
static void Main()
{
Simply += new dlgSimple(Welcome);
SayHello();
}
}

PROGRAM ON INDEXER’s

TO USE ARRAY WITHOUT ARRAY NAME i.e. to use the array values
using class objects.

using System;
using System.Collections;
public class demoindexer
{
public int[] arr = new int[5];
public Hashtable arr1 = new Hashtable();

public int this[int x]


{
set
{
arr[x]=value;
}
get
{
return arr[x];
}
}

public string this[string name]


{
set
{
arr1[name]=value;
}
get
{
return (string) arr1[name];
}
}

32
}
class test
{
static void Main()
{
demoindexer d = new demoindexer();
d.arr[0]=10;
d[1]=100; //indexer
demoindexer d1 = new demoindexer();
d1["first"]="sam";
d1["sec"]="sameer";
d1["third"]="pavan";
Console.WriteLine("The value of first pocket in array is:{0}",d.arr[0]);
Console.WriteLine("The value of second pocket using indexer is:{0}",d[1]);
Console.WriteLine("The value of 1,2 & 3 pocket using indexer is:{0}, {1} &
{2}",d1["first"],d1["sec"],d1["third"]);
}
}

PROGRAM ON ADO.NET IN CONSOLE APPLICATIONS

using System;
using System.Data.SqlClient;
using System.Data;

class Class1
{

static void Main()


{
SqlConnection cn = new SqlConnection("server=ECAS;uid=sa;database=PUBS;");
cn.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from Employee",cn);

DataSet ds = new DataSet(); //dataset created

adp.Fill(ds,"Employee"); //employee table filled in dataset


DataTable tbl = new DataTable("Employee");
tbl= ds.Tables[0];

foreach(DataRow i in tbl.Rows)
{
foreach(DataColumn j in tbl.Columns)
{
String str=Convert.ToString(i[j]);

33
Console.Write((str.PadRight(8,' ')));
}
Console.WriteLine(" ");
}
cn.Close();
}
}

PROGRAM ON IO FILES i.e. reading of a text files


using System;
using System.IO;

class test
{
static void Main()
{
//StreamReader sr = new StreamReader("D:\\anil\\csharp\\notes.txt");
StreamReader sr = new StreamReader(@"D:\anil\csharp\notes.txt");
String str="";
while(str != null)
{
Console.WriteLine(str);
str=sr.ReadLine();
}
sr.Close();
}
}

PROGRAM ON IO FILES i.e. creation of a text files

using System;
using System.IO;

class test
{
static void Main()
{
StreamWriter sw = new StreamWriter(@"d:\anil\csharp\notes1.txt");
String str="";
Console.WriteLine("Enter some text to be entered into the file:");
str=Console.ReadLine();
Console.WriteLine(str);
sw.Write(str);
sw.Close();
}

34
}
PROGRAM ON IO FILES i.e. creation of a new text files by coping existing files

using System;
using System.IO;
class Tester
{
private void Run( ) //user defined function
{
FileInfo f = new FileInfo(@"D:\anil\csharp\notes.txt");
StreamReader sr = f.OpenText( );
StreamWriter sw = new StreamWriter(@"D:\anil\csharp\notes2.txt");
string text;
do
{
text = sr.ReadLine( );
sw.WriteLine(text);
Console.WriteLine(text);
} while (text != null);
sr.Close( );
sw.Close( );
}
public static void Main( )
{
Tester t = new Tester( );
t.Run( );
}
}

PROGRAM ON IO FILES i.e. reading a file and displaying total line numbers

using System;
using System.IO;
class LineAtATime
{
static void LinePrint(Stream src) //user defined function
{
StreamReader r = new StreamReader(src);
int line = 0;
string aLine = "";
while ((aLine = r.ReadLine()) != null)
{
Console.WriteLine("{0}: {1}", line++, aLine);
}
}
public static void Main(string[] args)

35
{
foreach(string fName in args)
{
Stream src = new BufferedStream(new FileStream(fName, FileMode.Open));
LinePrint(src);
src.Close();
}
}
}

PROGRAM ON IO FILES i.e. reading a text file and check the existence and delete the file

using System;
using System.IO;

public class FileClass


{
static void ReadFromFile(string filename) //user defined function
{
StreamReader SR;
string S;
SR=File.OpenText(filename);
S=SR.ReadLine();
while(S!=null)
{
Console.WriteLine(S);
S=SR.ReadLine();
}
FileInfo f = new FileInfo(filename);
SR.Close();
if(f.Exists)
{
f.Delete();
Console.WriteLine("file is deleted");
}
}
public static void Main()
{
ReadFromFile("d:\\anil\\csharp\\notes2.txt");
}
}

36
PROGRAM ON IO FILES i.e. appending contents into an existing file

using System;
using System.IO;

public class FileClass


{
public static void Main()
{
AppendToFile();
}
static void AppendToFile()
{
StreamWriter SW;
SW=File.AppendText(@"d:\\satish\\csharp\\notes.txt");
SW.WriteLine("This Line Is Appended");
SW.Close();
Console.WriteLine("Text Appended Successfully");
}
}

PROGRAM ON IO FILES i.e. copying a file using fileinfo class object

using System;
using System.IO;

public class CopyingAFile


{
static void Main(string[] args)
{
FileInfo MyFile = new FileInfo(@"d:\anil\csharp\notes1.txt");

//MyFile.CopyTo(@"d:\anil\csharp\notes2.txt");
//or
MyFile.CopyTo(@"d:\anil\csharp\notes2.txt", true);
}
}

PROGRAM ON IO FILES i.e. moving the file location from one to another.
using System;
using System.IO;

public class CopyingAFile


{
static void Main(string[] args)

37
{
FileInfo MyFile = new FileInfo(@"d:\anil\csharp\notes2.txt");

MyFile.MoveTo(@"d:\anil\notes33.txt");
//or
//MyFile.MoveTo(@"d:\anil\notes33.txt", true);
}
}

PROGRAM ON READING THE CONTENTS OF THE FILES AND CREATING A NEW


DIRECTORY AND DISPLAYING DATE OF CREATION

using System;
using System.IO;

class test
{
static void Main()
{
FileInfo[] F;
int cnt=0;
DirectoryInfo di = new DirectoryInfo(".");

F=di.GetFiles("*.cs");

foreach(FileInfo t in F)
{
Console.WriteLine(t);
cnt++;
}

Console.WriteLine("{0} - Files are exists",cnt);


DateTime info = Directory.GetCreationTime(@"D:\satish");
Console.WriteLine("This direcotry is created on: "+info.ToString());

Directory.CreateDirectory(@"d:\satish\test");
DateTime info1 = Directory.GetCreationTime(@"D:\satish\test");
Console.WriteLine("This direcotry is created on: "+info1.ToString());

}
}

38
Object Serialization

This state is maintained in memory. Object Serialization is the process of reducing an object
instance into a format that can either be stored to disk or transported over a network. This
process is achieved so that the object can be recreated with its current state at a later point of
time or at a different location.

The object is persisted to disk using a particular formatter and sent across the network to another
co-operating machine which then receives the stream of data and deserializes it to get back the
object with its state unchanged.

PROGRAM ON SERIALIZES i.e. to create the dll file

using System;
namespace Serialization
{
[Serializable]
public class Test
{
public string name;
public int phno;
}
}

PROGRAM ON SERIALIZES i.e. to serialize a file using dll file in binary format

using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using Serialization;
namespace binex
{
class demo
{
static void Main(string[] args)
{
Test t = new Test();
t.name="sameer";
t.phno=2557070;
Stream mystr =File.OpenWrite("D:\\anil\\csharp\\binserialization.dat");
BinaryFormatter f = new BinaryFormatter();
f.Serialize(mystr,t);
mystr.Close();
}
}

39
}
PROGRAM ON SERIALIZES i.e. to deserialize a file using dll file in binary format
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
//using Serialization;

namespace Serialization
{
class demo
{
static void Main(string[] args)
{
FileStream file = new FileStream("d:\\anil\\binserialization.txt", FileMode.Open);
BinaryFormatter f = new BinaryFormatter();
Test t = f.Deserialize(file) as Test;
Console.WriteLine(t.name);
Console.WriteLine(t.phno);
Console.ReadLine();
}
}
}

PROGRAM ON SERIALIZES i.e. to serialize a file using dll file in xml format

using System;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;

namespace Serialization
{
class demo
{
static void Main(string[] args)
{
Test t = new Test();
t.name="sam";
t.phno=2557070;
Stream mystr = File.OpenWrite("d:\\anil\\csharp\\binserialization2.xml");
SoapFormatter f = new SoapFormatter();
f.Serialize(mystr,t);
mystr.Close();
}
}
}

40
PROGRAM ON SERIALIZES i.e. to deserialize a file using dll file in xml format

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization;

namespace Serialization
{
class demo
{
static void Main(string[] args)
{
FileStream file = new FileStream("d:\\anil\\csharp\\binserialization2.xml", FileMode.Open);
SoapFormatter f = new SoapFormatter();
Test t = (Test) f.Deserialize(file);
Console.WriteLine(t.name);
Console.WriteLine(t.phno);
Console.ReadLine();
}
}
}

 Remoting -: A remote object is an object that runs on the server. The remote client calls the
methods of the remote object with the help of a proxy. It cannot call these objects directly. In
.NET it is very easy to differentiate remote objects from local objects.

THIS PROGRAM USED TO CREATE DLL FILE WHICH IS USED IN BOTH SERVER
AS WELL AS CLIENT PROGRAM

using System;
namespace Rem1Ex1
{
public class MyClass:System.MarshalByRefObject
{
public MyClass()
{
Console.WriteLine("This is the Constructor of MyClass");
}

public void HelloWorld()


{
Console.WriteLine("A Big Hello To The World!");
}

41
}
}

THIS IS SERVER PROGRAM

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using Rem1Ex1;

namespace Rem1Ex2
{
class MyServer
{
static void Main(string[] args)
{
TcpServerChannel channel = new TcpServerChannel(8080);
ChannelServices.RegisterChannel(channel);

RemotingConfiguration.RegisterWellKnownServiceType(typeof(MyClass),
"HelloWorld", WellKnownObjectMode.SingleCall);

Console.WriteLine("Press ENTER To Stop Server!");


Console.ReadLine();
}
}
}

//To execute this file the class library created in the remote1example need to be referenced.

THIS IS CLIENT PROGRAM

using System;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using Rem1Ex1;

namespace Rem1Ex3
{
class MyClient
{
static void Main(string[] args)

42
{
ChannelServices.RegisterChannel(new TcpClientChannel());
MyClass obj =
(MyClass)Activator.GetObject(typeof(MyClass),"tcp://localhost:8080/HelloWorld");

int cnt=0;
for(cnt=0;cnt<5;cnt++)
{
obj.HelloWorld();
}
}
}
}

CRYPTOGRAPHY i.e. encryption and decryption of a text file

using System;
using System.IO;
using System.Security.Cryptography;

class SecretCode
{
string fileName;

string FileName{
set {
fileName = value;
}
get {
return fileName;
}
}

RijndaelManaged rm;
//Each algorithm has both a base class named after the algorithm (DES, Rijndael,RSA,
etc.) and an implementation of that algorithm provided by Microsoft.

SecretCode(string fName)
{
fileName = fName;
rm = new RijndaelManaged();
}

void EncodeToFile(string outName)


{
FileStream src = new FileStream(fileName, FileMode.Open);

43
ICryptoTransform encoder = rm.CreateEncryptor();
CryptoStream str = new CryptoStream(src, encoder, CryptoStreamMode.Read);

FileStream outFile = new FileStream(outName, FileMode.Create);


int i = 0;

while ((i = str.ReadByte()) != -1)


{
outFile.WriteByte((byte)i);
}
src.Close();
outFile.Close();
}

void Decode(string cypherFile)


{
FileStream src = new FileStream(cypherFile, FileMode.Open);
ICryptoTransform decoder =rm.CreateDecryptor();
CryptoStream str = new CryptoStream(src, decoder, CryptoStreamMode.Read);
int i = 0;
while ((i = str.ReadByte()) != -1)
{
Console.Write((char) i);
}
src.Close();
}
public static void Main(string[] args)
{
SecretCode sc = new SecretCode(args[0]);
sc.EncodeToFile("encoded.dat");
Console.WriteLine("Decoded:");
sc.Decode("encoded.dat");
}
}

EXAMPLE ON THREAD CONCEPT-1

using System;
using System.Threading;

class Class1
{
static void disp()
{
Console.WriteLine("Hello, from thread {0}", Thread.CurrentThread.Name);

44
}
public void ThreadStart()
{
disp();
}

static void Main(string[] args)


{
Thread.CurrentThread.Name = "Main thread";
Class1 obj = new Class1();
Thread thread = new Thread( new ThreadStart(obj.ThreadStart));
thread.Name = "Thread 1";
thread.Start();
}
}

EXAMPLE ON THREAD CONCEPT-2 use of join function

using System;
using System.Threading;
class Class1
{
//public void disp()
static void disp()
{
for (int i=0;i<10;i++)
{
Console.WriteLine("Value {0}", i);
Thread.Sleep(100);
}
}
static void Main(string[] args)
{
Class1 obj = new Class1();
Thread t1 = new Thread(new ThreadStart(disp));
t1.Start();
Thread.Sleep(2000);
t1.Join(); // wait until the thread is completed
Console.WriteLine("Goodbye");
}
}

SYNCHRONIZATION
When your Visual Basic .NET programs use multiple threads, the applications may encounter
errors due to race conditions that occur when two or more threads require synchronized access to
a shared resource. To prevent race conditions from leading to errors, inVisual Basic .NET

45
programs we can use the SyncLock statement to protect shared resources. Using the SyncLock
statement, a user can prevent one thread from accessing a shared resource until the current thread
“unlocks” the object. To use the SyncLock statement, you must specify a variable, upon which
you want your code to apply a lock.

using System;
using System.Threading;

public class demo


{
public void disp()
{
int i=0;
lock(this)
while(i<=10)
{
Console.WriteLine(i);
i++;
Console.WriteLine(Thread.CurrentThread.Name);
Thread.Sleep(500);
}
}
}
class test
{
static void Main()
{
demo d = new demo();
ThreadStart job = new ThreadStart(d.disp);
ThreadStart job1 = new ThreadStart(d.disp);
Thread t1 = new Thread(job);
Thread t2 = new Thread(job1);
t1.Start();
t1.Name="Thread1";
t2.Name="Thread2";
t2.Start();
}
}

EXAMPLE ON MULTITHREADING USING MONITOR CONCEPT

//Demonstrates dining philosophers problem


using System;

46
using System.Threading;
enum Desire {
Pontificate, Eating
}
class Table {
readonly int iDiners = 5;
Diner[] diners;
Chopstick[] chopsticks;

Table(){
diners = new Diner[iDiners];
diners[0] = new Diner("Lovelace","The difference engine rocks the most.");
diners[1] = new Diner("Hejlsberg","C# rules, ok?");
diners[2] = new Diner("Stroustrup","C++ is still the fastest");
diners[3] = new Diner("Gosling","Write once, run anywhere!");
diners[4] = new Diner("van Rossum","Brackets are bad");
chopsticks = new Chopstick[iDiners];
for (int i = 0; i < iDiners; i++) {
Chopstick c = new Chopstick();
chopsticks[i] = c;
diners[i].LeftChopstick = c;
diners[(i + 1) % iDiners].RightChopstick = c;
}
}
public static void Main(){
new Table();
}
}
class Diner {
readonly int basePonderTime = 1000; //10;
readonly int ponderTimeRand = 0;
readonly int baseEatTime = 1000; //10;
readonly int eatTimeRand = 0;
readonly int postEatTime = 1000; //10;
readonly int betweenChopstickTime = 1500; //50;
readonly int maxStartupDelay = 1000; //150;
readonly int starvationTimeout = 1000; //100;
static int totalMealsEaten = 0;
string name;
internal string Name{
get{ return name;}
}
string opinion;
Thread myThread;
Chopstick left;
internal Chopstick LeftChopstick{

47
set { left = value;}
get{ return left;}
}
Chopstick right;
internal Chopstick RightChopstick{
set{ right = value;}
get{ return right;}
}
Desire desire = Desire.Pontificate;
static Random r = new Random();
internal Diner(string name, string opinion){
this.name = name;
this.opinion = opinion;
ThreadStart ts = new ThreadStart(EatAndTalk);
myThread = new Thread(ts);
myThread.Start();
}
void EatAndTalk(){
Thread.Sleep(r.Next(maxStartupDelay));
while (true) {
if (desire == Desire.Eating) {
Eat();
} else {
Pontificate();
}
}
}
void Pontificate(){
Console.WriteLine(name + ": " + opinion);
Thread.Sleep(basePonderTime +
r.Next(ponderTimeRand));
desire = Desire.Eating;
}
void Eat(){
GetChopsticks();
Console.WriteLine(name + ": Eating");
Thread.Sleep(baseEatTime + r.Next(eatTimeRand));
Console.WriteLine(name + ": Burp");
Thread.Sleep(postEatTime);
ReleaseChopsticks();
Interlocked.Increment(ref totalMealsEaten);
desire = Desire.Pontificate;
}
void GetChopsticks()
{
Console.WriteLine(name+ ": Picking up left chopstick");

48
left.Pickup(this);
Thread.Sleep(betweenChopstickTime);
Console.WriteLine(name + ": Picking up right chopstick");
right.Pickup(this);
}
void ReleaseChopsticks(){
left.Putdown();
right.Putdown();
}
internal void Wait(int id){
Console.WriteLine(name
+ ": Waiting for chopstick[{0}]", id);
try {
Thread.Sleep(starvationTimeout);
Console.WriteLine(name
+ " starved to death waiting for "
+ " chopstick[{0}]", id);
Console.WriteLine("Meals served: "
+ totalMealsEaten);
myThread.Abort();
} catch (ThreadInterruptedException) {
}
}
internal void Interrupt(int id){
myThread.Interrupt();
Console.WriteLine(name
+ ": alerted to availability of "
+ "chopstick[{0}]", id);
}
}
class Chopstick {
static int counter = 0;
int id = counter++;
bool acquired = false;
Diner waitingFor = null;
internal void Pickup(Diner d){
if (acquired == true) {
waitingFor = d;
//Must wait
d.Wait(id);
}
acquired = true;
Console.WriteLine(d.Name
+ ": Got chopstick[{0}]", id);
}
internal void Putdown(){

49
Console.WriteLine(
"Chopstick[{0}] released", id);
acquired = false;
if (waitingFor != null) {
Console.WriteLine("Someone's waiting");
waitingFor.Interrupt(id);
}
waitingFor = null;
}}

ORACLE CONNECTIVITY-
Provider=MSDAORA.1;User ID=scott;PASSWORD=TIGER;Data
Source=oracle8i

50

Anda mungkin juga menyukai