OOPS C#

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
<pre lang="x-c# C#

Formating

using System;
namespace Converter
{
public class demo2
{

public static void Main(string[] args)
{
int x = 50;
Console.Write("the simple text formating");
Console.Write("nthe simple text formating" + " next " + (x+10).ToString());
Console.Write("nthe sum {0} and {1} is {2}", x ,40, x+40);
Console.Write("n"indent for left {0, -10}"", 9);
Console.Write("nindent for right {0, 10} " , 9);
Console.Write("ncurrency - {0:C1} {1:C7}", 88.888 ,8.88888);
Console.Write("n decimal Integer - {0:D10}" ,889123 );
Console.Write("nExpontential - {0:E} ", 8128.888 );
Console.Write("nFixed point - {0:F3}" , 8.88888234);
Console.Write("ngeneral - {0:G}" , 8123.8884567);
Console.Write("nnumber - {0:N}" , 82312312.888237);
Console.Write("nHexadecimal - {0:X9}" , 2388345);
Console.ReadLine();
}
}
}

Access Specifiers

First file

using System;
namespace access
{
public class class1
{
public string publica = " is public ";
private string priaveta = " is priavte ";
protected string prota = " is protected ";
protected internal string protina = " is protected inertnal ";
internal string ina = " is internal ";
public void display()
{
Console.WriteLine(publica);
Console.WriteLine(prota);
Console.WriteLine(priaveta);
Console.WriteLine(protina);
Console.WriteLine(ina);
}

}
public class class2
{
class1 c = new class1();
public void display()
{
Console.WriteLine(c.publica);
//Console.WriteLine(c.prota);
// Console.WriteLine(c.priaveta);
Console.WriteLine(c.protina);
Console.WriteLine(c.ina);
}

}
public class class3:class1
{
public void display3()
{
Console.WriteLine(publica);
Console.WriteLine(prota);
// Console.WriteLine(c.priaveta);
Console.WriteLine(protina);
Console.WriteLine(ina);
}

}

}

second file

using System;
using access;
namespace y
{
class class4 : class1
{
public void display2()
{
Console.WriteLine(publica);
Console.WriteLine(prota);
// Console.WriteLine(c.priaveta);
Console.WriteLine(protina);
// Console.WriteLine(ina);
}

}
class class5
{
class1 c = new class1();
public void display()
{
Console.WriteLine(c.publica);
// Console.WriteLine(prota);
// Console.WriteLine(c.priaveta);
// Console.WriteLine(protina);
// Console.WriteLine(ina);
}

}
class displayinginfo
{
public static void Main()
{
class1 obj1 = new class1();
class2 obj2 = new class2();
class3 obj3 = new class3();
class4 obj4 = new class4();
class5 obj5 = new class5();
Console.WriteLine("from main class");
obj1.display();
Console.WriteLine("from other class in same assembly");
obj2.display();
Console.WriteLine("from derived class in same assembly");
obj3.display3();
Console.WriteLine("from derived class in other assembly");
obj4.display2();
Console.WriteLine("from anyother class in other assembly");
obj5.display();
Console.ReadLine();
}
}
}

running instructions
C:abcdin>csc /target:library protectedinternal.cs
C:abcdin>csc /reference:protectedinternal.dll use.cs


Function Parameters

using System;
public class SwapNumber
{
void SwapNum(ref int a, ref int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void SwapNum2(out int a, ref int b)
{
a = b;
b = 23;
}
static void Main(string[] args)
{
SwapNumber classobj = new SwapNumber();
int Number1, Number2;
Console.WriteLine("Enter the first number");
Number1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number");
Number2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The value of first number is {0}", Number1);
Console.WriteLine("The value of second number is {0}", Number2);
classobj.SwapNum(ref Number1, ref Number2);
Console.WriteLine("Now the value of first number after swaping is {0}", Number1);
Console.WriteLine("Now the value of second number after swapping is {0}", Number2);
int n1, n2;
Console.WriteLine("Enter the second number");
n2 = Convert.ToInt32(Console.ReadLine());
classobj.SwapNum2(out n1, ref n2);
Console.WriteLine("Now the value of first number after swaping is {0}", n1);
Console.WriteLine("Now the value of second number after swapping is {0}", n2);
Console.ReadLine();
}
}

STRING FUNCTIONS

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string sample;
sample = "hi how r u ";
char f = sample[3];
Console.WriteLine(f);
sample = sample.Insert(2, ",hello");
Console.WriteLine(sample);
int len = sample.Length;
Console.WriteLine(len);
string s2;
s2 = String.Copy(sample);
Console.WriteLine(s2);
string sa = String.Concat("jsfhsjdfh", "sdafasd");
Console.WriteLine(sa);
string h = "sadfg" + "sdfh";
Console.WriteLine(h);
sample = sample.Trim();
Console.WriteLine(sample);
Console.WriteLine(sample.ToUpper());
Console.WriteLine(sample.ToLower());
int comp;
comp = String.Compare(sample, s2, true );
Console.WriteLine(comp);
Console.ReadLine();
}
}
}


BOXING

using System;

public class Class1
{
public static vopid main()
{
int p = 123;
object box;
box = p;
//box = (object) p;
int x;
x = (int)box;
}
}

ARRAY

using System;
namespace LargestSmallest
{
class Program
{
static void Main(string[] args)
{
int n;
int[] a = new int[5];
Console.WriteLine("Enter the size of Array");
string s = Console.ReadLine();
n = Int32.Parse(s);
Console.WriteLine("Enter the array elements");
for (int i = 0; i < n; i++)
{
string s1 = Console.ReadLine();
a = Int32.Parse(s1);
}
Console.Write("");
Console.WriteLine("the array");
foreach (int x in a)
{
Console.WriteLine(x);
}
System.Array.Sort(a);
Console.WriteLine("the array after sorting");
foreach (int x in a)
{
Console.WriteLine(x);
}
int[] b = (int[])a.Clone();
int[] c = a;
Console.WriteLine("the clone array");
for( int i = 0; i < n; i++)
{
Console.WriteLine(b);
}
Console.WriteLine("the copy array");
for (int i = 0; i < n; i++)
{
Console.WriteLine(b);
}
a[0] = 1234;
Console.WriteLine("the array after changing");
for (int i = 0; i < n; i++)
{
Console.WriteLine(a);
}
Console.WriteLine("the clone array after changing");
for (int i = 0; i < n; i++)
{
Console.WriteLine(b);
}
Console.WriteLine("the copy array changing");
for (int i = 0; i < n; i++)
{
Console.WriteLine(b);
}
int length = a.Length;
Console.WriteLine(" the length of the array is" + length);
Console.ReadLine();
}
}
}


Function Parameter

using System;
public class SwapNumber
{
void SwapNum(ref int a, ref int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void SwapNum2(out int a, ref int b)
{
a = 23;
b = b+1;
}
static void Main(string[] args)
{
SwapNumber classobj = new SwapNumber();
int Number1, Number2;
Console.WriteLine("Enter the first number");
Number1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number");
Number2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The value of first number is {0}", Number1);
Console.WriteLine("The value of second number is {0}", Number2);
classobj.SwapNum(ref Number1, ref Number2);
Console.WriteLine("Now the value of first number after swaping is {0}", Number1);
Console.WriteLine("Now the value of second number after swapping is {0}", Number2);
int n1, n2;
Console.WriteLine("Enter the second number");
n2 = Convert.ToInt32(Console.ReadLine());
classobj.SwapNum2(out n1, ref n2);
Console.WriteLine("Now the value of first number after swaping is {0}", n1);
Console.WriteLine("Now the value of second number after swapping is {0}", n2);
Console.ReadLine();
}
}


Array List

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace enumdays
{
class Program
{
static void Main(string[] args)
{
ArrayList a = new ArrayList();
a.Add(23);
a.Add("kasdhfhjsd");
a.Add(k);
a.Add(34);
//a.Sort();
a.Reverse();
foreach (object x in a)
{
Console.WriteLine(x.ToString());
}
Console.ReadLine();

}
}
}

Enum


using System;
using System.Collections.Generic;
using System.Text;

namespace enumdays
{
class Program
{
enum days { Sat, Sun, Mon, Tue, Wed, Thu= 17, Fri };
static void Main(string[] args)
{
int First = (int)days.Sat;
int Last = (int)days.Fri;
Console.WriteLine(" value of sat {0} and of Fri {1} ", First, Last);
Console.WriteLine(days.Fri);
Console.ReadLine();
}
}
}

Params

using System;
using System.Collections.Generic;
using System.Text;

namespace enumdays
{
class Program
{
public static int pramsample(params int[] L)
{
int total = 0;
foreach (int I in L)
{
total += I;
}
return total / L.Length;
}
static void Main(string[] args)
{
int avg1 = pramsample(6, 7, 8, 9);
int avg2 = pramsample(1, 2,3,4,5,6,7,8,9);
Console.WriteLine(avg1);
Console.WriteLine(avg2);
Console.Read();
}
}
}

Static variables and function

using System;
public class Class1
{
public int a;
public static int b;
public static void Init()
{
b = 0;
}
public static void count()
{
b++;
}
public void Init2()
{
a = 0;
}
public void count2()
{
count();
a++;
}
}

class entrypoint
{
public static void Main()
{
Class1 c = new Class1();
c.Init2();
Console.WriteLine(c.a);
Console.WriteLine(Class1.b);
c.count2();
Console.WriteLine(c.a);
Console.WriteLine(Class1.b);
Class1 c1 = new Class1();
c1.Init2();
c1.count2();
Console.WriteLine(c1.a);
Console.WriteLine(Class1.b);
}
}


Overloading functions

using System;
using System.Collections.Generic;
using System.Text;

namespace overloading
{
class Program
{
static void func()
{
int a = 90;
Console.WriteLine(a+10);
}
static void func(int a)
{
Console.WriteLine(a+10);
}
static void func(double a)
{
Console.WriteLine(a+10);
}
static void func(int a, int b)
{
Console.WriteLine(a+b);
}
static void func(double a, int b)
{
Console.WriteLine(a*b);
}
static void func(int a , double b)
{
Console.WriteLine(a + b);
}
static void Main(string[] args)
{
int x, y;
double z;
x = 15;
y = 34;
z = 9.4567;
func();
func(x);
func(x, y);
func(z);
func(x, z);
func(z, x);

Console.Read();
}
}
}


Operator Overloading

First
using System;
namespace Printing
{
class Book
{
int NumberOfPages;

public void PrintPages()
{
Console.WriteLine("Now, the total number of pages in a book is " + NumberOfPages);
}
public void GetPages()
{
Console.WriteLine("Enter the number of pages you want to add in the book:");
NumberOfPages = Convert.ToInt16(Console.ReadLine());
}
public static Book operator +(Book b1, int Value)
{
b1.NumberOfPages += Value;
return b1;
}
public static void Main()
{
Book b1 = new Book();
Console.WriteLine("The number of pages in the book is 1000");
b1.GetPages(); //Accepts data
b1 += 1000;
b1.PrintPages();
Console.ReadLine();
}
}
}

Second


using System;
namespace FunCityLand
{
class Distance
{
int Length;
public Distance()
{
Length = 0;
}
public static Distance operator +(Distance d1, Distance d2)
{
Distance d3 = new Distance();
d3.Length = d1.Length + d2.Length;
return d3;
}
public void DisplayDistance()
{
Console.WriteLine("The total distance is {0}", this.Length);
}
public void get()
{
Console.WriteLine("Enter the distance length for distance");
Length = Convert.ToInt32(Console.ReadLine());
}
}
class EntryPoint
{
public static void Main()
{
Distance Distance1 = new Distance();
Distance Distance2 = new Distance();
Distance Distance3 = new Distance();
Distance1.get();

Distance2.get();
Distance3 = Distance1 + Distance2;
Distance3.DisplayDistance();
}
}
}
Third

using System;
namespace FunCityLand
{
class Distance
{
int Length;
public Distance()
{
Length = 0;
}
public static Distance operator ++(Distance d1)
{
Distance d3 = new Distance();
d3.Length = d1.Length + 1;
return d3;
}
public void DisplayDistance()
{
Console.WriteLine("The total distance is {0}", this.Length);
}
public void get()
{
Console.WriteLine("Enter the distance length for distance");
Length = Convert.ToInt32(Console.ReadLine());
}

}
class EntryPoint
{
public static void Main()
{
Distance Distance1 = new Distance();
Distance1.get();
Distance d2 = Distance1++;
Distance1.DisplayDistance();
d2.DisplayDistance();
d2 = ++Distance1;
Distance1.DisplayDistance();
d2.DisplayDistance();
}
}
}

Fourth
using System;
namespace FunCityLand
{
struct Distance
{
int Length;
public static Distance operator ++(Distance d1)
{
d1.Length ++;
return d1;
}
public void DisplayDistance()
{
Console.WriteLine("The total distance is {0}", this.Length);
}
public void get()
{
Console.WriteLine("Enter the distance length for distance");
Length = Convert.ToInt32(Console.ReadLine());
}

}
class EntryPoint
{
public static void Main()
{
Distance Distance1 = new Distance();
Distance1.get();
Distance d2 = Distance1++;
Distance1.DisplayDistance();
d2.DisplayDistance();
d2 = ++Distance1;
Distance1.DisplayDistance();
d2.DisplayDistance();
}
}
}

Structure constructor

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace enumdays
{
namespace ConsoleApplication4
{
public struct sample
{
public int a;
public int b;
//public sample()
public sample(int x, int y)
{
this.a = x;
this.b = y;
}
public sample(int x)
{
this.a = x;
this.b = 12;
}

}
class Program
{
static void Main(string[] args)
{
sample s1 = new sample();
Console.WriteLine(s1.a + " " + s1.b);
sample s3 = new sample(15);
Console.WriteLine(s3.a + " " + s3.b);
sample s2 = new sample(2, 3);
Console.WriteLine(s2.a + " " + s2.b);
Console.ReadLine();
}
}
}
}


Passing class as referencein function

using System;
public class sample
{
public int a, b;
public void passvalue(sample s)
{
s = new sample();
s.a = 90;
s.b = 34;
}
public void passref(ref sample s)
{
s = new sample();
s.a = 90;
s.b = 34;
}
public void passout(out sample s)
{
s = new sample();
s.a = 90;
s.b = 34;
}
}
public class usage
{
static void Main()
{
sample b1 = new sample();
sample b2 = new sample();
b1.a = 78;
b1.b= 89;
b1.passvalue(b1);
Console.WriteLine(b1.a );
b1.passref(ref b1);
Console.WriteLine(b1.a );
b1.passout(out b2);
Console.WriteLine(b2.a );

}
}

Intializer

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication4
{
public class sample
{
public int num1;
public int num2;
public sample():this(2,3)
{
}
public sample(int x , int y)
{
this.num1 = x;
this.num2 = y;
}
}

class Program
{
static void Main(string[] args)
{
sample s1 = new sample();
sample s2 = new sample(4,5);
Console.WriteLine(s1.num1 + " " + s1.num2 );
Console.WriteLine(s2.num1 + " " + s2.num2);
Console.ReadLine();
}
}
}


Chaining

using System;
public class Book
{
private string a, b;
public Book SetAuthor(string au)
{
this.a = au;
return this;
}
public Book mine(string m)
{
this.b = m;
return this;
}
}
public class usage
{
static void Main()
{
Book b = new Book();
b.SetAuthor("folwer").mine("kl");
}
}

String functions

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string sample;
sample = "hi how r u ";
char f = sample[3];
Console.WriteLine(f);
sample = sample.Insert(2, ",hello");
Console.WriteLine(sample);
int len = sample.Length;
Console.WriteLine(len);
string s2;
s2 = String.Copy(sample);
Console.WriteLine(s2);
string sa = String.Concat("jsfhsjdfh", "sdafasd");
Console.WriteLine(sa);
string h = "sadfg" + "sdfh";
Console.WriteLine(h);
sample = sample.Trim();
Console.WriteLine(sample);
Console.WriteLine(sample.ToUpper());
Console.WriteLine(sample.ToLower());
int comp;
comp = String.Compare(sample, s2, true );
Console.WriteLine(comp);
Console.ReadLine();
}
}
}

Abstract Class

using System;

namespace DrawShapes
{
public abstract class DrawingObject
{
public abstract void Draw();

}
public class Line : DrawingObject
{
public override void Draw()
{
Console.WriteLine("Im a Line.");
}
}

public class Circle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("Im a Circle.");
}
}

public class Square : DrawingObject
{
public override void Draw()
{
Console.WriteLine("Im a Square.");
}
}

public class DrawDemo
{
public static int Main(string[] args)
{
DrawingObject[] dObj = new DrawingObject[3];
dObj[0] = new Line();
dObj[1] = new Circle();
dObj[2] = new Square();
foreach (DrawingObject drawObj in dObj)
{
drawObj.Draw();
}
Console.ReadLine();
return 0;
}
}
}

Ineterface

using System;
namespace CalculateArea
{
interface Area
{
void calcArea(double Radius);


void calcVolume(int Side);
}

public class CircleCube:Area
{
public void calcArea(double Radius)
{
double Pie = 3.14;
double Result;
Result = Pie*Radius*Radius;
Console.WriteLine("The Area of a circle is: {0}",Result);
}
public void calcVolume(int Side)
{
int Result;
Result = Side*Side*Side;
Console.WriteLine("The Volume of a cube is: {0}",Result);
}

}
class class1
{
public static void Main(string[] args)
{
CircleCube obj = new CircleCube();
double Radius;
int Side;
Console.WriteLine("Enter the radius of the circle");
Radius = Convert.ToDouble(Console.ReadLine());
obj.calcArea(Radius);
Console.WriteLine("Enter the side of the cube");
Side = Convert.ToInt32(Console.ReadLine());
obj.calcVolume(Side);
Console.ReadLine();
}
}
}
Second


using System;

namespace CalculateArea
{
interface Area
{
void calcArea(double Radius);
void calcVolume(int Side);
}
public class CircleCube : Area
{
void Area.calcArea(double Radius)
{
double Pie = 3.14;
double Result;
Result = Pie * Radius * Radius;
Console.WriteLine("The Area of a circle is: {0}", Result);
}
void Area.calcVolume(int Side)
{
int Result;
Result = Side * Side * Side;
Console.WriteLine("The Volume of a cube is: {0}", Result);
}
public void run1
{
((Area)this).calcArea();
Area.calcVolume();
}
}
class class1
{
public static void Main(string[] args)
{
CircleCube obj = new CircleCube();
double Radius;
int Side;
Console.WriteLine("Enter the radius of the circle");
Radius = Convert.ToDouble(Console.ReadLine());
//obj.calcArea(Radius);
Console.WriteLine("Enter the side of the cube");
Side = Convert.ToInt32(Console.ReadLine());
obj.run1();
//obj.calcVolume(Side);
Console.ReadLine();
}
}
}

Inner Classes

using System;

public class Book
{
private string a, b;
public void outerfunc()
{}
public class inside
{
private int insidevar;
private void insidefunc()
{
}
public void intwo()
{
}
}
}
public class usage
{
static void Main()
{
Book b = new Book();
b.outerfunc();
Book.inside i = new Book.inside();
i.intwo();
i.insidefunc();
}
}

Overriding functions

using System;
namespace over
{
public class starter
{
public static void Main()
{
y obj = new y();
obj.MethA();

z obj1 = new z();
obj1.MethA();

z obj3 = new y();
obj3.MethA();

}
}
public class z
{
public virtual void MethA()
{
Console.WriteLine(" from z ");
}
}
public class y: z
{
public override void MethA()
{
Console.WriteLine(" from y ");
}
}
}

Shadowing Functions


using System;
namespace over
{
public class starter
{
public static void Main()
{
y obj = new y();
obj.MethA();

z obj1 = new z();
obj1.MethA();

z obj3 = new y();
obj3.MethA();
Console.ReadLine();

}
}
public class z
{
public void MethA()
{
Console.WriteLine(" from z ");
}
}
public class y: z
{
new public void MethA()
{
Console.WriteLine(" from y ");
}
}
}

File handling

using System;
using System.IO;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
Fileex f = new Fileex();
f.write();
f.read();
}
}
class Fileex
{
public void write()
{
FileStream fs = new FileStream("myfile.txt", FileMode.Append, FileAccess.Write);
StreamWriter w = new StreamWriter(fs);
Console.WriteLine("enter a string");
string str = Console.ReadLine();
w.Write(str);
w.Flush();
w.Close();
fs.Close();
}
public void read()
{
FileStream fs = new FileStream("myfile.txt", FileMode.Open , FileAccess.Read );
StreamReader r = new StreamReader(fs);
r.BaseStream.Seek(0, SeekOrigin.Begin);
string str = r.ReadLine();
while(str !=null)
{
Console.WriteLine(str);
str = r.ReadLine();
}
r.Close();
fs.Close();
Console.ReadLine();
}
}
}

Second

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ConsoleApplication5
{
class implfilesystem
{
private string s1;
private static DirectoryInfo mydir;
public implfilesystem(string s)
{
s1 = s;
mydir = new DirectoryInfo(s1);
}
public void createdir()
{
if (!mydir.Exists)
{
mydir.Create();
Console.WriteLine("directory created");
}
else
{
Console.WriteLine("directory exists");
}
}
public void createsubdir(String dir)
{
if (mydir.Exists)
{
mydir.CreateSubdirectory(dir);
Console.WriteLine("subdirectory created");
}
else
{
Console.WriteLine("subdirectory not created because parent doesnot exists");
}
}
public void delsubdir(String dirname)
{
String temp;
temp = mydir + "\" + dirname;
DirectoryInfo d = new DirectoryInfo(temp);
d.Delete();
}
public void getdir()
{
if (mydir.Exists)
{
DirectoryInfo[] d = mydir.GetDirectories();
foreach (DirectoryInfo d1 in d)
{
Console.WriteLine(d1.FullName);
}
}

}
public void getfiles()
{
if (mydir.Exists)
{
FileInfo[] f = mydir.GetFiles();
foreach (FileInfo f1 in f)
{
Console.WriteLine(f1.FullName);
}
}
}
public void createfile(String fname)
{
if (mydir.Exists)
{
String x = mydir + "\" + fname;
FileInfo f = new FileInfo(x);
if (!f.Exists)
{
FileStream fx = f.Create();
fx.Close();

}
else
{
Console.WriteLine("file exists");
}
}
else
{
Console.WriteLine("directory doesnot exist");
}
}
public void deletefile(String fname)
{
if (mydir.Exists)
{
String x = mydir + "\" + fname;
FileInfo f = new FileInfo(x);
if (f.Exists)
{
f.Delete();
Console.WriteLine("delete file");
}

}
}
}
class Program
{
static void Main(string[] args)
{
String s;
Console.WriteLine("please enter the directory name with path");
s =Console.ReadLine();
implfilesystem i = new implfilesystem(s);
i.createdir();
Console.WriteLine("please enter sub directory name ");
s = Console.ReadLine();
i.createsubdir(s);
Console.WriteLine("please enter the file name ");
s = Console.ReadLine();
i.createfile(s);
i.getdir();
i.getfiles();
Console.WriteLine("please enter the file name to delete");
s = Console.ReadLine();
i.deletefile(s);
Console.WriteLine("please enter the directory name to delete");
s = Console.ReadLine();
i.delsubdir(s);
Console.ReadLine();
}
}
}


Third

using System;
using System.IO;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
Fileex f = new Fileex();
f.write();
f.read();
}
}
class Fileex
{
public void write()
{
FileStream fs = new FileStream("myfile.txt", FileMode.Append, FileAccess.Write);
BinaryWriter w = new BinaryWriter(fs);
Console.WriteLine("enter a string");
string str = Console.ReadLine();
w.Write(str);
Console.WriteLine("enter a number");
int a = Convert.ToInt32(Console.ReadLine());
w.Write(a);
Console.WriteLine("enter a Decimal");
double b = Convert.ToDouble(Console.ReadLine());
w.Write(b);
bool c = true;
w.Write(b);
w.Flush();
w.Close();
fs.Close();
}
public void read()
{
FileStream fs = new FileStream("myfile.txt", FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
r.BaseStream.Seek(0, SeekOrigin.Begin);
string str = r.ReadString();
int a = r.ReadInt32();
double b = r.ReadDouble();
bool c = r.ReadBoolean();
Console.WriteLine(str);
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
r.Close();
fs.Close();
Console.ReadLine();
}
}
}

Exception Handling


using System;

namespace mine
{
class example
{
static void Main()
{
Counter c = new Counter();
try
{
c.doaverage();
}
catch( Exception ex)
{
Console.WriteLine( " Cought the Exception {0}" , ex.Message);
}
finally
{
Console.WriteLine("the finally block");
}
Console.ReadLine();
}
}

public class Counter
{
int sum = 0;
int count = 0;
int average =0;
public void doaverage()
{
try
{
average = sum/count;
}
catch(Exception ex)
{
throw ex;
}
}
}
}


Second

using System;

namespace mine
{
class example
{
static void Main()
{
Counter c = new Counter();
try
{
c.doaverage();
}
catch( Exception ex)
{
Console.WriteLine( " Cought the Exception {0}" , ex.Message);
}
finally
{
Console.WriteLine("the finally block");
}
Console.ReadLine();
}
}
public class myexception : ApplicationException
{
public myexception(string message): base(message){}
}
public class Counter
{
int sum = 0;
int count = 0;
int average =0;
public void doaverage()
{
if(count ==0)
{
throw(new myexception("Divide with zero not possible"));
}
}
}
}

Threading

First

namespace ConsoleApplication1
{

class Class1
{

static void Main(string[] args)
{
//starting thread delgate, mapps a thread to its start function
ThreadStart mine = new ThreadStart(threadcall);
Thread th = Thread.CurrentThread;
th.Name = " Main thread" ;
Console.WriteLine(th.Name);

Console.ReadLine();
}
}
}

Second

using System;
using System.Threading;
namespace ConsoleApplication1
{
class Class1
{
public static void threadcall()
{
Console.WriteLine(" from child Thread");
}

static void Main(string[] args)
{
//starting thread delgate, mapps a thread to its start function
ThreadStart mine = new ThreadStart(threadcall);
Thread th = Thread.CurrentThread;
th.Name = " Main thread" ;
Console.WriteLine(th.Name);
Thread child = new Thread(mine);
child.Start();
child.Name="child Thread";
Console.WriteLine("main starts the child");
Console.WriteLine(child.Name);
Console.ReadLine();
}
}
}

Third

using System;
using System.Threading;
namespace ConsoleApplication1
{

class Class1
{
public static void threadcall()
{
Console.WriteLine(" from child Thread");
}

static void Main(string[] args)
{
//starting thread delgate, mapps a thread to its start function
ThreadStart mine = new ThreadStart(threadcall);
Thread th = Thread.CurrentThread;
th.Name = " Main thread" ;
Console.WriteLine(th.Name);
Thread child = new Thread(mine);
child.Start();
child.Name="child Thread";
Console.WriteLine("main starts the child");
Console.WriteLine("main sleeps and child will finish execution in meanwhile");
Thread.Sleep(4000);
Console.WriteLine("control back to main");
Console.ReadLine();
}
}
}

Fourth

using System;
using System.Threading;
namespace ConsoleApplication1
{

class Class1
{

public static void first()
{
Console.WriteLine(" from child Thread 1");
for( int i =0 ; i<20; i++)
{
Console.WriteLine("first " + i);

}
}

public static void second()
{
Console.WriteLine(" from child Thread 2");
for( int i =0 ; i<20; i++)
{
Console.WriteLine("second " + i);

}
}
[STAThread]
static void Main(string[] args)
{
//starting thread delgate, mapps a thread to its start function
ThreadStart mine1 = new ThreadStart(first);
ThreadStart mine2 = new ThreadStart(second);

Console.WriteLine("Main");
Thread child1 = new Thread(mine1);
Thread child2 = new Thread(mine2);
child1.Start();
child2.Start();
Console.WriteLine("main starts the child");
Console.WriteLine("main sleeps and child will finish execution in meanwhile");
Thread.Sleep(1000);
Console.WriteLine("control back to main");
Console.ReadLine();
}
}
}

Fifth

using System;
using System.Threading;
namespace ConsoleApplication1
{

class Class1
{
public static void threadcall()
{
try
{
Console.WriteLine(" from child Thread");
for( int i =0 ; i<20; i++)
{
Console.WriteLine("Child Thread " + i);
Thread.Sleep(1000);
}

}
catch(ThreadAbortException e)
{
Console.WriteLine("Exception");
}
finally
{
Console.WriteLine("finally exceuted");
}
}
[STAThread]
static void Main(string[] args)
{
//starting thread delgate, mapps a thread to its start function
ThreadStart mine = new ThreadStart(threadcall);
Thread th = Thread.CurrentThread;
th.Name = " Main thread" ;
Console.WriteLine(th.Name);
Thread child = new Thread(mine);
child.Start();
child.Name="child Thread";
Console.WriteLine("main starts the child");
Console.WriteLine("main sleeps and child will finish execution in meanwhile");
Thread.Sleep(4000);
Console.WriteLine("control back to main");
child.Abort();
Console.WriteLine(" main aborts child");
Console.ReadLine();
}
}
}

Sixth

using System;
using System.Threading;
namespace ConsoleApplication1
{

class Class1
{
public static void first()
{
Console.WriteLine(" from child Thread 1");
for( int i =0 ; i<10; i++)
{
Console.WriteLine("first " + i);
}
}
public static void second()
{
Console.WriteLine(" from child Thread 2");
for( int i =0 ; i<10; i++)
{
Console.WriteLine("second " + i);
}
}
[STAThread]
static void Main(string[] args)
{
//starting thread delgate, mapps a thread to its start function
ThreadStart mine1 = new ThreadStart(first);
ThreadStart mine2 = new ThreadStart(second);

Console.WriteLine("Main");
Thread child1 = new Thread(mine1);
Thread child2 = new Thread(mine2);
child1.Start();
child2.Start();
Console.WriteLine("main starts the child");
Console.WriteLine("main sleeps and child will finish execution in meanwhile");
child2.Priority= ThreadPriority.Highest;
child1.Priority= ThreadPriority.Lowest;
Console.WriteLine("control back to main");
Console.ReadLine();
}
}
}

Seventh

using System;
using System.Threading;
namespace ConsoleApplication1
{

class Class1
{

public void res()
{
Monitor.Enter(this);
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);

}
Monitor.Exit(this);
}
public void first()
{
Console.WriteLine("first");
res();
}

public void second()
{
Console.WriteLine("second");
res();
}
}

class enter
{
static void Main(string[] args)
{
//starting thread delgate, mapps a thread to its start function
Class1 c = new Class1();
ThreadStart mine1 = new ThreadStart(c.first);
ThreadStart mine2 = new ThreadStart(c.second);
Console.WriteLine("Main");
Thread child1 = new Thread(mine1);
Thread child2 = new Thread(mine2);
child2.Start();
child1.Start();
Console.WriteLine("main starts the child");
Console.WriteLine("main sleeps and child will finish execution in meanwhile");
Console.WriteLine("control back to main");
Console.ReadLine();
}
}
}

Eigth

using System;
using System.Threading;
namespace ConsoleApplication1
{

class Class1
{

public void res()
{
lock(this)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);

}
}
}
public void first()
{
Console.WriteLine("first");
res();
}

public void second()
{
Console.WriteLine("second");
res();
}
}

class enter
{
static void Main(string[] args)
{
//starting thread delgate, mapps a thread to its start function
Class1 c = new Class1();
ThreadStart mine1 = new ThreadStart(c.first);
ThreadStart mine2 = new ThreadStart(c.second);
Console.WriteLine("Main");
Thread child1 = new Thread(mine1);
Thread child2 = new Thread(mine2);
child2.Start();
child1.Start();
Console.WriteLine("main starts the child");
Console.WriteLine("main sleeps and child will finish execution in meanwhile");
Console.WriteLine("control back to main");
Console.ReadLine();
}
}
}

Delegates and events

using System;
using System.Collections.Generic;
using System.Text;

namespace delgates
{
class Program
{
public delegate void func(int a, int b);
public static void add(int x, int y)
{
Console.WriteLine(x + y);
}
public static void sub(int x, int y)
{
Console.WriteLine(x - y);
}
public static void mul(int x, int y)
{
Console.WriteLine(x * y);
}
public static void div(int x, int y)
{
Console.WriteLine(x / y);
}
static void Main(string[] args)
{
func f = new func(add);
f+= new func(sub);
f+= new func(mul);
f+= new func(div);
int m = 23;
int n = 6;
f(m, n);
f -= new func(sub);
f -= new func(div);
f(m, n);
Console.Read();
}
}
}

Second

using System;
using System.IO;

namespace AttendanceApp
{
// Event Publisher
public class DelegateEvent
{
public delegate void AttendanceLogHandler(string Message);
public event AttendanceLogHandler EventLog;
public void LogProcess()
{

Console.WriteLine("Enter your name");
string UserName = Console.ReadLine();
OnEventLog("Logging the info :" + UserName);
}
protected void OnEventLog(string Message)
{
if (EventLog != null)
{
EventLog(Message);
}
}
}

//Subscriber of the Event
public class RecordAttendance
{
static void Logger(string LogInfo)
{
Console.WriteLine(LogInfo);
}

static void Main(string[] args)
{
DelegateEvent DEvent = new DelegateEvent();
DEvent.EventLog += new DelegateEvent.AttendanceLogHandler(Logger);
DEvent.LogProcess();
Console.ReadLine();

}
}
}

Attributes

using System;
using System.Reflection;

namespace AttribNamespace
{
// create DescriptionAttribute custom attribute to be assigned to class members
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[DescriptionAttribute("This class contains defination of Description attribute", 1.0)]
public class DescriptionAttribute : System.Attribute
{
// attribute constructor for positional parameters

public DescriptionAttribute(string Description, double Version)
{
this.description= Description;
this.version= Version;
}
protected String description;
public String Description
{
get
{
return this.description;
}
}
protected Double version;
public Double Version
{
get
{
return this.version;
}

set
{
this.version = value;
}
}
}

[DescriptionAttribute("This class contains two methods", 1.0)]
public class Calculator
{
public double Add(Double num1, Double num2)
{
return num1 + num2;
}

public double Subtract(Double num1, Double num2)
{
return num1 - num2;
}

public double Multiply(Double num1, Double num2)
{
return num1 * num2;
}

public double Divide(Double num1, Double num2)
{
return num1 / num2;
}
}

public class EntryPoint
{
public static void Main()
{
Calculator m = new Calculator();
Console.WriteLine(" the sum is {0} ", m.Add(23.5 , 67.89));

Console.ReadLine();
}
}
}


Second

using System;
using System.Reflection;

namespace AttribNamespace
{
// create DescriptionAttribute custom attribute to be assigned to class members
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[DescriptionAttribute("This class contains defination of Description attribute", 1.0)]
public class DescriptionAttribute : System.Attribute
{
// attribute constructor for positional parameters

public DescriptionAttribute(string Description, double Version)
{
this.description= Description;
this.version= Version;
}
protected String description;
public String Description
{
get
{
return this.description;
}
}
protected Double version;
public Double Version
{
get
{
return this.version;
}

set
{
this.version = value;
}
}

}

[DescriptionAttribute("This class contains two methods", 1.0)]
public class Calculator
{

public double Add(Double num1, Double num2)
{
return num1 + num2;
}

public double Subtract(Double num1, Double num2)
{
return num1 - num2;
}

public double Multiply(Double num1, Double num2)
{
return num1 * num2;
}

public double Divide(Double num1, Double num2)
{
return num1 / num2;
}
}

[DescriptionAttribute("This class contains the Main method", 2.0)]
public class EntryPoint
{
public static void Main()
{
Calculator MyObj = new Calculator();
Console.WriteLine("The sum of specified two nos are: {0}", MyObj.Add(15, 20.5));

Type type = typeof(Calculator);

// Specific call should me made to retrieve an attribute properties
// when two or more custom attributes are there in an application
foreach (Object attributes in type.GetCustomAttributes(typeof(DescriptionAttribute),false))
{
DescriptionAttribute MyDAObj = (DescriptionAttribute)attributes;
if (null != MyDAObj)
{
Console.WriteLine("nClass : Calculator - Description :{0} - Version {1}", MyDAObj.Description, MyDAObj.Version);
}
}
type = null;
type = typeof(EntryPoint);
foreach (Object attributes in type.GetCustomAttributes(false))
{
DescriptionAttribute MyDAObj = (DescriptionAttribute)attributes;
Console.WriteLine("nClass : EntryPoint - Description :{0} - Version {1}", MyDAObj.Description, MyDAObj.Version);
}
Console.ReadLine();
}
}
}

Third

using System;
using System.Reflection;

namespace Lesson13_Ex
{

// create BugFixingAttribute custom attribute to be assigned to class members
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)]
[DescriptionAttribute("This class contains defination of Bug Fixing attribute", 2.0)]
public class BugFixingAttribute : System.Attribute
{
private int bugNo;
private string developer;
private string dateFixed;
public string remarks;
// attribute constructor for positional parameters

public BugFixingAttribute(int BugNo, string Developer, string DateFixed)
{
this.bugNo = BugNo;
this.developer = Developer;
this.dateFixed = DateFixed;
}

public int BugNo
{
get
{
return bugNo;
}
}
public string DateFixed
{
get
{
return dateFixed;
}
}
public string Developer
{
get
{
return developer;
}
}
public string Remarks
{
get
{
return remarks;
}
set
{
remarks = value;
}
}
}

// create DescriptionAttribute custom attribute to be assigned to class members
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[DescriptionAttribute("This class contains defination of Description attribute", 1.0)]
public class DescriptionAttribute : System.Attribute
{
// attribute constructor for positional parameters

public DescriptionAttribute(string Description, double Version)
{
this.description = Description;
this.version = Version;
}
protected String description;
public String Description
{
get
{
return this.description;
}
}
protected Double version;
public Double Version
{
get
{
return this.version;
}

set
{
this.version = value;
}
}

}

[BugFixingAttribute(125, "Sara Levo", "08/15/06", Remarks = "Return object not specified")]
[BugFixingAttribute(159, "Sara Levo", "08/17/06", Remarks = "Data Type Mismatch")]
[DescriptionAttribute("This class contains two methods", 1.0)]
public class Calculator
{

public double Add(Double num1, Double num2)
{
return num1 + num2;
}

public double Subtract(Double num1, Double num2)
{
return num1 - num2;
}

[BugFixingAttribute(155, "Sara Levo", "08/16/06")]
public double Multiply(Double num1, Double num2)
{
return num1 * num2;
}

[BugFixingAttribute(156, "Sara Levo", "08/16/06")]
public double Divide(Double num1, Double num2)
{
return num1 / num2;
}
}

[DescriptionAttribute("This class contains the Main method", 2.0)]
public class EntryPoint
{
public static void Main()
{
Calculator MyObj = new Calculator();
Console.WriteLine("The sum of specified two nos are: {0}", MyObj.Add(15, 20.5));

Type type = typeof(Calculator);

// iterating through the attributes of the Calculator class
foreach (Object attributes in type.GetCustomAttributes(typeof(BugFixingAttribute), false))
{
BugFixingAttribute MyBFAObj = (BugFixingAttribute)attributes;
if (null != MyBFAObj)
{
Console.WriteLine("nBug #: {0}", MyBFAObj.BugNo);
Console.WriteLine("Developer: {0}", MyBFAObj.Developer);
Console.WriteLine("Date Fixed: {0}", MyBFAObj.DateFixed);
Console.WriteLine("Remarks: {0}", MyBFAObj.Remarks);
}
}

// iterating through the attributes of all the methods of a Calculator class
foreach (MethodInfo method in type.GetMethods())
{
foreach (Attribute attributes in method.GetCustomAttributes(true))
{
BugFixingAttribute MyBFAObjM = (BugFixingAttribute)attributes;
if (null != MyBFAObjM)
{
Console.WriteLine("nBug #: {0} for Method: {1}", MyBFAObjM.BugNo, method.Name);
Console.WriteLine("Developer: {0}", MyBFAObjM.Developer);
Console.WriteLine("Date Fixed: {0}", MyBFAObjM.DateFixed);
Console.WriteLine("Remarks: {0}", MyBFAObjM.Remarks);
}
}
}

foreach (Object attributes in type.GetCustomAttributes(typeof(DescriptionAttribute), false))
{
DescriptionAttribute MyDAObj = (DescriptionAttribute)attributes;
if (null != MyDAObj)
{
Console.WriteLine("nClass : Calculator - Description :{0} - Version {1}", MyDAObj.Description, MyDAObj.Version);
}
}
type = null;
type = typeof(EntryPoint);
foreach (Object attributes in type.GetCustomAttributes(false))
{
DescriptionAttribute MyDAObj = (DescriptionAttribute)attributes;
Console.WriteLine("nClass : EntryPoint - Description :{0} - Version {1}", MyDAObj.Description, MyDAObj.Version);
}
Console.ReadLine();
}
}
}




[/code]

View the full article
 
Back
Top