Program1:
using System;
namespace ArrayDemo1
{
class MainClass
{
public static void Main()
{
int[] i = new int[10];
//for (int x = 0; x < i.Length; x++)
//{
// Console.Write(“Enter {0} value:”, x + 1);
// i[x] = Convert.ToInt32(Console.ReadLine());
//}
//for (int j = 0; j < i.Length; j++)
//{
// Console.Write(“{0}\t”, i[j]);
//}
string[,] str ={ { “sankar”, “raju”, “phani” }, { “rani”, “Padma”, “pavani” } };
foreach (string s in str)
{
Console.Write(“\t{0}”, s);
}
Console.WriteLine();
Console.WriteLine(“Rank of i:” + i.Rank);
Console.WriteLine(“Rank of str” + str.Rank);
Console.WriteLine(“Length of Str” + str.Length);
Console.WriteLine(“Upperbound:” + str.GetUpperBound(0));
Console.WriteLine(“Upperbound:” + str.GetUpperBound(1));
Console.Read();
}
}
}
Program2:
using System;
namespace ArrayDemo2
{
class MainClass
{
public static void Main()
{
Array arr = Array.CreateInstance(typeof(string), 5);
arr.SetValue(“bdps”, 0);
arr.SetValue(“niit”, 1);
arr.SetValue(“cmts”, 2);
arr.SetValue(“aptech”,3);
arr.SetValue(“ssi”, 4);
foreach (string s in arr)
{
Console.Write(“{0}\t”, s);
}
}
}
}
Program3:
using System;
using System.Collections;
namespace ArrayDemo3
{
class MainClass
{
public static void Main()
{
Array arr3d = Array.CreateInstance(typeof(int), 2, 3, 4);
for (int i = 0; i <= arr3d.GetUpperBound(0); i++)
{
for (int j = 0; j <= arr3d.GetUpperBound(1); j++)
{
for(int k=0;k<=arr3d.GetUpperBound(2);k++)
{
arr3d.SetValue(i+j*10+k*100,i,j,k);
}
}
}
PrintValues(arr3d);
//foreach (int i in arr3d)
// Console.Write(“{0}\t”, i);
}
static void PrintValues(Array arr)
{
IEnumerator ie= arr.GetEnumerator();
int i = 0;
int col = arr.GetLength(arr.Rank – 1);
while (ie.MoveNext())
{
if (i < col)
{
i += 1;
}
else
{
i = 1;
Console.WriteLine();
}
Console.Write(“\t{0}”, ie.Current);
}
Console.WriteLine();
}
}
}
Program4:
using System;
namespace ArrayDemo4
{
class MainClass
{
public static void Main()
{
int[] i ={ 1, 2, 3, 4, 5 };
object[] obj ={ 99,98,97,96,95};
Console.WriteLine(“original values”);
PrintValues(i);
PrintValues(obj);
Array.Copy(i, obj, 2);
Console.WriteLine(“After First Copy”);
PrintValues(i);
PrintValues(obj);
Array.Copy(obj, obj.GetUpperBound(0) – 1,
i, i.GetUpperBound(0) – 1, 2);
Console.WriteLine(“After Second Copy”);
PrintValues(i);
PrintValues(obj);
}
public static void PrintValues(int[] arr)
{
Console.Write(“Int array:”);
foreach (int i in arr)
{
Console.Write(“\t{0}”, i);
}
Console.WriteLine();
}
public static void PrintValues(object[] arr)
{
Console.Write(“Object Array:”);
foreach (object obj in arr)
{
Console.Write(“\t{0}”, obj);
}
Console.WriteLine();
}
}
}
Program5:
using System;
namespace ArrayDemo6
{
public class MainClass
{
public static void Main()
{
Array arr = Array.CreateInstance(typeof(string), 10);
arr.SetValue(“Banu”, 0); arr.SetValue(“bujji”, 1);
arr.SetValue(“kalyan”, 2); arr.SetValue(“kasi”, 3);
arr.SetValue(“bujji”, 4); arr.SetValue(“kavya”, 5);
arr.SetValue(“bujji”, 6); arr.SetValue(“pavan”, 7);
arr.SetValue(“bujji”, 8); arr.SetValue(“rani”, 9);
Console.WriteLine(“First index:”+Array.IndexOf(arr,“bujji”));
Console.WriteLine(“next index:” + Array.IndexOf(arr, “bujji”,2));
Console.WriteLine(“next index:” + Array.IndexOf(arr, “bujji”,5,4));
Console.WriteLine();
Console.WriteLine(“Lastindex:” + Array.LastIndexOf(arr, “bujji”));
Console.WriteLine(“Lastindex:” + Array.LastIndexOf(arr, “bujji”,7));
Console.WriteLine(“Lastindex:” + Array.LastIndexOf(arr, “bujji”,5,4));
}
}
}
Program6:
using System;
using System.Collections;
namespace ArrayDemo7
{
class MainClass
{
public static void Main()
{
IComparer i = new RevClass();
string[] str ={ “sankar”,“zero”,“xerox”,“yahoo”,“ashok”,“phani”,“rani”,“bujji”,“kalyan”};
Console.WriteLine(“Oringinal values:”);
PrintValues(str);
Array.Sort(str, 1, 3);
PrintValues(str);
Console.WriteLine(“After Sorting…”);
Array.Sort(str);
PrintValues(str);
Console.WriteLine(“\nReverse order::”);
Array.Sort(str, 3, 4, i);
PrintValues(str);
Array.Sort(str, i);
PrintValues(str);
}
public static void PrintValues(Array arr)
{
foreach (string s in arr)
{
Console.Write(“{0}\t”, s);
}
Console.WriteLine();
}
}
class RevClass : IComparer
{
int IComparer.Compare(object x, object y)
{
return (new CaseInsensitiveComparer().Compare(y, x));
}
}
}
Program7:
using System;
namespace IndexerDemo
{
class Test
{
int[] arr = new int[100];
public int this[int index]
{
get
{
if (index < 0 || index >= 100)
return 0;
else
return arr[index];
}
set
{
if (!(index < 0 || index >= 100))
{
arr[index] = value;
}
}
}
}
class MainClass
{
public static void Main()
{
Test t = new Test();
t[0] = 150;
t[3] = 90;
t[6] = 190;
for (int i = 0; i <= 10; i++)
Console.WriteLine(“t[{0}]={1}”,i, t[i]);
}
}
}
Program8:
using System;
namespace ExceptionDemo
{
class MainClass
{
public static void Main()
{
int a, b, c;
try
{
Console.WriteLine(“Enter a value:”);
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(“Enter b value:”);
b = Convert.ToInt32(Console.ReadLine());
c = a / b;
Console.WriteLine(“The result is ::” + c);
}
catch (FormatException fe)
{
Console.WriteLine(“Error:\n” + fe.StackTrace);
}
catch (ArithmeticException oe)
{
Console.WriteLine(oe.Message);
}
catch (Exception e)
{
Console.WriteLine(“Exception :” + e.ToString());
}
finally
{
Console.WriteLine(“Thank Q”);
}
Console.WriteLine(“This is continued…”);
}
}
}
Program9:
using System;
namespace ExceptionDemo2
{
class MainClass
{
public static void Main()
{
string name;
Console.WriteLine(“Enter name:”);
name = Console.ReadLine();
try
{
if (name == “”)
name = null;
name= name.ToUpper();
Console.WriteLine(“Hai Mr./Mrs.:” + name);
}
catch (NullReferenceException ne)
{
Console.WriteLine(ne.Message);
}
}
}
}
Program10:
using System;
namespace ExceptionDemo3
{
class MainClass
{
public static void Main()
{
int a;
try
{
Console.Write(“Enter a number:”);
a = int.Parse(Console.ReadLine());
if (a < 0 || a > 5)
throw new IndexOutOfRangeException();
Console.WriteLine(“Your age is::” + a);
}
catch (FormatException ex)
{
Console.WriteLine(“Enter no.s only”);
}
catch (IndexOutOfRangeException io)
{
Console.WriteLine(“Your no must be between 0-5″);
}
}
}
}
Program11:
using System;
class MainClass
{
static void Main(string[] args)
{
MailToData MyData = new MailToData();
Console.Write(“Enter Your Name:”);
MyData.Name = Console.ReadLine();
Console.Write(“Enter Your Address:”);
MyData.Address = Console.ReadLine();
Console.Write(“Enter Your City, State, and Pin Program separated by spaces:”);
MyData.CityStatePin = Console.ReadLine();
Console.WriteLine(“Name: {0}”, MyData.Name);
Console.WriteLine(“Address: {0}”, MyData.Address);
Console.WriteLine(“City: {0}”, MyData.City);
Console.WriteLine(“State: {0}”, MyData.State);
Console.WriteLine(“Pin: {0}”, MyData.Pin);
Console.WriteLine(“The following address will be used:”);
Console.WriteLine(MyData.Address);
Console.WriteLine(MyData.CityStatePin);
}
}
public class MailToData
{
string name = ” “;
string address = ” “;
string citystatePin = ” “;
string city = ” “;
string state = ” “;
string pin = ” “;
public string Name
{
get { return name; }
set { name = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public string CityStatePin
{
get
{
return ReturnCityStatePin();
}
set
{
citystatePin = value;
ParseCityStatePin();
}
}
public string City
{
get { return city; }
set { city = value; }
}
public string State
{
get { return state; }
set { state = value; }
}
public string Pin
{
get { return pin; }
set { pin = value; }
}
private void ParseCityStatePin()
{
int CityIndex;
int StateIndex;
try
{
CityIndex = citystatePin.IndexOf(” “);
char[] CityArray = new char[CityIndex];
citystatePin.CopyTo(0, CityArray, 0, CityIndex);
StateIndex = citystatePin.LastIndexOf(” “);
char[] StateArray = new char[StateIndex - CityIndex];
citystatePin.CopyTo(CityIndex, StateArray, 0, (StateIndex – CityIndex));
char[] PinArray = new char[citystatePin.Length - StateIndex];
citystatePin.CopyTo(StateIndex, PinArray, 0, (citystatePin.Length – StateIndex));
city = new String(CityArray);
city = city.Trim(new char[] { ‘ ‘, ‘,’, ‘;’, ‘-’, ‘:’ });
state = new String(StateArray);
state = state.Trim(new char[] { ‘ ‘, ‘,’, ‘;’, ‘-’, ‘:’ });
Pin = new String(PinArray);
Pin = Pin.Trim(new char[] { ‘ ‘, ‘,’, ‘;’, ‘-’, ‘:’ });
}
catch (OverflowException)
{
Console.WriteLine(“\n\nYou must enter spaces between elements.\n\n”);
}
}
private string ReturnCityStatePin()
{
state = state.ToUpper();
string MyCityStatePin = String.Concat(city, “, “, state, ” “, Pin);
return MyCityStatePin;
}
}
Program12:
using System;
namespace StringDemo
{
public class StringTester
{
static void Main()
{
string s1 = “abcd”;
string s2 = “ABCD”;
string s3 = @”Liberty Associates, Inc.
provides custom .NET development,
on-site Training and Consulting”;
int result;
result = string.Compare(s1, s2);
Console.WriteLine(“comprecompare s1: {0}, s2: {1}, result: {2}\n”,
s1, s2, result);
result = string.Compare(s1, s2, true);
Console.WriteLine(“compare insensitive\n”);
Console.WriteLine(“s1: {0}, s2: {1}, result: {2}\n”,
s1, s2, result);
string s6 = string.Concat(s1, s2);
Console.WriteLine(
“s6 concatenated from s1 and s2: {0}”, s6);
// //string s7 = s1 + s2;
// //Console.WriteLine(
// //”s7 concatenated from s1 + s2: {0}”, s7);
string s8 = string.Copy(s6);
Console.WriteLine(
“s8 copied from s7: {0}”, s8);
string s9 = s8;
Console.WriteLine(“s9 = s8: {0}”, s9);
Console.WriteLine(
“\nDoes s9.Equals(s8)?: {0}”,
s9.Equals(s8));
Console.WriteLine(
“Does Equals(s9,s8)?: {0}”, string.Equals(s9, s8));
Console.WriteLine(
“Does s9==s8?: {0}”, s9 == s8);
Console.WriteLine(
“\nString s9 is {0} characters long. “,
s9.Length);
Console.WriteLine(
“The 5th character is {1}\n”,
s9.Length, s9[4]);
Console.WriteLine(“s3:{0}\nEnds with Training?: {1}\n”,
s3,
s3.EndsWith(“Training”));
Console.WriteLine(
“Ends with Consulting?: {0}”,
s3.EndsWith(“Consulting”));
Console.WriteLine(
“\nThe first occurrence of Training “);
Console.WriteLine(“in s3 is {0}\n”,
s3.IndexOf(“Training”));
//string s10 = s3.Insert(102, “excellent “);
//Console.WriteLine(“s10: {0}\n”, s10);
string s11 = s3.Insert(s3.IndexOf(“Training”),
“excellent “);
Console.WriteLine(“s11: {0}\n”, s11);
}
}
}
Program13:
using System;
namespace ExceptionDemo5
{
class MyException:ApplicationException
{
public MyException(string str):base(str)
{
}
public string MyMethod()
{
return “Your Balance must be >=(greaterthan or equalto) 1000″;
}
}
class MainClass
{
public static void Main()
{
double cbal, wd=0.0;
cbal = 5000;
while (true)
{
Console.Write(“Enter Withdrawl amount:”);
try
{
wd = Convert.ToDouble(Console.ReadLine());
}
catch
{
Console.WriteLine(“Enter Numbers Only”);
}
try
{
if ((cbal – wd) >= 1000)
{
Console.WriteLine(“Your Transaction Processed Successfully\nYour withdrawlamount={0}\nPresent balance={1}”, wd, (cbal – wd));
return;
}
else
{
throw new MyException(“Error in withdrawl amount”);
}
}
catch (MyException me)
{
Console.WriteLine(me.MyMethod());
Console.WriteLine(me.Message);
Console.WriteLine(me.StackTrace);
}
}
}
}
}
Program14:
using System;
using System.IO;
namespace ExceptionDemo6
{
class Test
{
public FileStream getFileStream(string path)
{
try
{
FileStream f = File.Open(path, FileMode.Open);
return f;
}
catch (FileNotFoundException fe)
{
throw fe;
}
}
}
class MainClass
{
public static void Main()
{
Test t = new Test();
try
{
t.getFileStream(“c:\\hai.txt”);
Console.WriteLine(“File opened successfully”);
}
catch (FileNotFoundException fe)
{
Console.WriteLine(“Handled in mainclass\n”+fe.Message );
}
}
}
}
Program15:
using System;
class Sample
{
enum Color { Yellow = 10, Blue, Green };
static DateTime thisDate = DateTime.Now;
public static void Main()
{
string s = “”;
Console.Clear();
Console.WriteLine(“Standard Numeric Format Specifiers”);
s = String.Format(
“(C) Currency: . . . . . . . . {0:C}\n” +
“(D) Decimal:. . . . . . . . . {0:D}\n” +
“(E) Scientific: . . . . . . . {1:E}\n” +
“(F) Fixed point:. . . . . . . {1:F}\n” +
“(G) General:. . . . . . . . . {0:G}\n” +
“ (default):. . . . . . . . {0} (default = ‘G’)\n” +
“(N) Number: . . . . . . . . . {0:N}\n” +
“(P) Percent:. . . . . . . . . {1:P}\n” +
“(R) Round-trip: . . . . . . . {1:R}\n” +
“(X) Hexadecimal:. . . . . . . {0:X}\n”,
-123, -123.45f);
Console.WriteLine(s);
Console.WriteLine(“Standard DateTime Format Specifiers”);
s = String.Format(
“(d) Short date: . . . . . . . {0:d}\n” +
“(D) Long date:. . . . . . . . {0:D}\n” +
“(t) Short time: . . . . . . . {0:t}\n” +
“(T) Long time:. . . . . . . . {0:T}\n” +
“(f) Full date/short time: . . {0:f}\n” +
“(F) Full date/long time:. . . {0:F}\n” +
“(g) General date/short time:. {0:g}\n” +
“(G) General date/long time: . {0:G}\n” +
“ (default):. . . . . . . . {0} (default = ‘G’)\n” +
“(M) Month:. . . . . . . . . . {0:M}\n” +
“(R) RFC1123:. . . . . . . . . {0:R}\n” +
“(s) Sortable: . . . . . . . . {0:s}\n” +
“(u) Universal sortable: . . . {0:u} (invariant)\n” +
“(U) Universal sortable: . . . {0:U}\n” +
“(Y) Year: . . . . . . . . . . {0:Y}\n”,
thisDate);
Console.WriteLine(s);
Console.WriteLine(“Standard Enumeration Format Specifiers”);
s = String.Format(
“(G) General:. . . . . . . . . {0:G}\n” +
“ (default):. . . . . . . . {0} (default = ‘G’)\n” +
“(F) Flags:. . . . . . . . . . {0:F} (flags or integer)\n” +
“(D) Decimal number: . . . . . {0:D}\n” +
“(X) Hexadecimal:. . . . . . . {0:X}\n”,
Color.Green);
Console.WriteLine(s);
}
}
Program16:
using System;
namespace ObjectClone
{
class Point:ICloneable
{
public int x, y;
public Point()
{
}
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public override string ToString()
{
return string.Format(“X={0},Y={1}”, x, y);
//return “X=” + x + “,y=” + y;
}
public object Clone()
{
return this.MemberwiseClone();
}
}
class MainClass
{
static void Main()
{
Point p = new Point(10, 20);
Point p2=(Point) p.Clone();
p2.x = 500; p.y = 999;
Console.WriteLine(“p value:”+p.ToString());
Console.WriteLine(“p2 value:”+p2.ToString());
}
}
}
Program17:
using System;
namespace ObjectClone2
{
class Point:ICloneable
{
public int x, y;
public pDescription pd= new pDescription();
public Point() { }
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public Point(int x, int y, string name)
{
this.x = x;
this.y = y;
pd.petName = name;
}
public object Clone()
{
//return this.MemberwiseClone();
Point p = (Point)this.MemberwiseClone();
pDescription pd1 = new pDescription();
pd1.petName = p.pd.petName;
pd1.g = p.pd.g;
p.pd = pd1;
return p;
}
public override string ToString()
{
return string.Format(“X={0},Y={1},PetName={2}\nId={3}”, x, y, pd.petName, pd.g);
}
}
class pDescription
{
public string petName;
public Guid g;
public pDescription()
{
petName = “No Name”;
g = Guid.NewGuid();
}
}
class MainClass
{
public static void Main()
{
Point p = new Point(10, 20, “sankar”);
Point p2 = ( Point)p.Clone();
p2.x = 999; p2.pd.g = Guid.NewGuid();
p2.pd.petName = “prasad”;
Console.WriteLine(p.ToString());
Console.WriteLine();
Console.WriteLine(p2.ToString());
}
}
}
Program18:
using System;
using System.Text;
namespace StringDemo12
{
class MainClass
{
static void Main()
{
int i = 500;
StringBuilder sb = new StringBuilder(“Hello World”);
sb.Append(“!”);
sb.AppendFormat(“{0:c}”,i );
sb.Replace(‘!’, ‘?’);
sb.Insert(6, “Beautiful “);
Console.WriteLine(sb);
sb.Remove(6, 10);
Console.WriteLine(sb);
Console.WriteLine(“length:” + sb.Length);
}
}
}
Program19:
using System;
using System.Collections.Generic;
using System.Text;
namespace FormattableVector
{
class MainEntryPoint
{
static void Main()
{
Vector v1 = new Vector(1, 32, 5);
Vector v2 = new Vector(845.4, 54.3, -7.8);
Console.WriteLine(“\nIn IJK format,\nv1 is {0,30:IJK}\nv2 is {1,30:IJK}”, v1, v2);
Console.WriteLine(“\nIn default format,\nv1 is {0,30}\nv2 is {1,30}”, v1, v2);
Console.WriteLine(“\nIn VE format\nv1 is {0,30:VE}\nv2 is {1,30:VE}”, v1, v2);
Console.WriteLine(“\nNorms are:\nv1 is {0,20:N}\nv2 is {1,20:N}”, v1, v2);
}
}
struct Vector : IFormattable
{
public double x, y, z;
public Vector(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
public string ToString(string format, IFormatProvider formatProvider)
{
if (format == null)
return ToString();
string formatUpper = format.ToUpper();
switch (formatUpper)
{
case “N”:
return “|| “ + Norm().ToString() + ” ||”;
case “VE”:
return String.Format(“( {0:E}, {1:E}, {2:E} )”, x, y, z);
case “IJK”:
StringBuilder sb = new StringBuilder(x.ToString(), 30);
sb.Append(” i + “);
sb.Append(y.ToString());
sb.Append(” j + “);
sb.Append(z.ToString());
sb.Append(” k”);
return sb.ToString();
default:
return ToString();
}
}
public override string ToString()
{
return “( “ + x + ” , “ + y + ” , “ + z + ” )”;
}
public double Norm()
{
return x * x + y * y + z * z;
}
}
}
Program20:
using System;
using System.Collections.Generic;
using System.Text;
namespace AnonymousDelegate
{
delegate decimal CalculateBonus(decimal sales);
class Employee
{
public string name;
public decimal sales;
public decimal bonus;
public CalculateBonus calculation_algorithm;
}
class Program
{
static decimal CalculateStandardBonus(decimal sales)
{
return sales / 10;
}
static void Main(string[] args)
{decimal multiplier = 2;
CalculateBonus standard_bonus = new CalculateBonus(CalculateStandardBonus);
CalculateBonus enhanced_bonus = delegate(decimal sales) { return multiplier * sales / 10; };
Employee[] staff = new Employee[5];
for (int i = 0; i < 5; i++)
staff[i] = new Employee();
staff[0].name = “Mr Apple”;
staff[0].sales = 100;
staff[0].calculation_algorithm = standard_bonus;
staff[1].name = “Ms Banana”;
staff[1].sales = 200;
staff[1].calculation_algorithm = standard_bonus;
staff[2].name = “Mr Cherry”;
staff[2].sales = 300;
staff[2].calculation_algorithm = standard_bonus;
staff[3].name = “Mr Date”;
staff[3].sales = 100;
staff[3].calculation_algorithm = enhanced_bonus;
staff[4].name = “Ms Elderberry”;
staff[4].sales = 250;
staff[4].calculation_algorithm = enhanced_bonus;
foreach (Employee person in staff)
PerformBonusCalculation(person);
foreach (Employee person in staff)
DisplayPersonDetails(person);
}
public static void PerformBonusCalculation(Employee person)
{
person.bonus = person.calculation_algorithm(person.sales);
}
public static void DisplayPersonDetails(Employee person)
{
Console.WriteLine(person.name);
Console.WriteLine(person.bonus);
Console.WriteLine(“—————”);
}
}
}
Program21:
using System;
namespace DelegateDemo
{
public delegate void MyDel();
class MyClass
{
public void Sample()
{
Console.WriteLine(“This is sample method”);
}
public static void Greetings()
{
Console.WriteLine(“Greetings from Bdps”);
}
}
class MainClass
{
static void Main()
{
MyClass m = new MyClass();
MyDel m1 = new MyDel(m.Sample);
m1();
MyDel m2 = new MyDel(MyClass.Greetings);
m2.Invoke();
}
}
}
Program22:
using System;
namespace DelegateDemo2
{
public delegate void DelSalary();
class Emp
{
public string name;
public double salary;
public void SetSalary()
{
Console.WriteLine(“Enter name:”);
name = Console.ReadLine();
Console.Write(“Enter salary”);
salary = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(“Salary:” + salary);
}
}
class Bonus : Emp
{
public double bonus;
public new void SetSalary()
{
if (salary < 5000)
{
bonus = 1000;
}
else
{
bonus = 0;
}
salary += bonus;
Console.WriteLine(“Salary:” + salary);
}
}
class MainClass
{
public static void Main()
{
Bonus b = new Bonus();
DelSalary d1 = new DelSalary(((Emp)b).SetSalary);
DelSalary d2 = new DelSalary(b.SetSalary);
d1.Invoke();
d2.Invoke();
}
}
}
Program23:
using System;
namespace DelegateDemo3
{
public delegate void myDel(double d);
class MyClass
{
public void DoubleMethod(double a)
{
Console.WriteLine(2 * a);
}
public void SquareMethod(double s)
{
Console.WriteLine(s * s);
}
}
class MainClass
{
static void Main()
{
MyClass m = new MyClass();
myDel d1, d2, d3, d4;
d1 = new myDel(m.DoubleMethod);
d2 = new myDel(m.SquareMethod);
d1(5); d2(5);
d3 = d1 + d2;
d3.Invoke(3);
d4 = d3 – d1;
d4.Invoke(12);
}
}
}
Program24:
using System;
namespace DelegateDemo4
{
public delegate decimal CalculateBonus(decimal sales);
class Emp
{
public string name;
public decimal sales;
public decimal bonus;
public CalculateBonus cb;
}
class MainClass
{
static decimal StandardBonus(decimal sales)
{
return sales / 10;
}
public static void Main()
{
decimal m = 2;
CalculateBonus cb1 = new CalculateBonus(StandardBonus);
CalculateBonus cb2 = delegate(decimal sales)
{
return m* sales / 10;
};
Emp[] e = new Emp[3];
for (int i = 0; i < 3; i++)
e[i] = new Emp();
e[0].name = “sankar”;
e[0].sales = 1000;
e[0].cb = cb1;
e[1].name = “prasad”;
e[1].sales = 1000;
e[1].cb = cb2;
e[2].name = “kumar”;
e[2].sales = 2000;
e[2].cb = cb2;
foreach (Emp e1 in e)
setBonus(e1);
foreach (Emp e1 in e)
Display(e1);
}
public static void setBonus(Emp e)
{
e.bonus = e.cb(e.sales);
}
public static void Display(Emp e)
{
Console.WriteLine(“Name:” + e.name);
Console.WriteLine(“sales:” + e.sales);
Console.WriteLine(“Bonus:” + e.bonus);
}
}
}
Program25:
using System;
namespace EventDemo
{
public delegate void MyDel();
interface Iinf
{
event MyDel MyEvent;
void FireEvent();
}
class EventClass : Iinf
{
public event MyDel MyEvent;
public void FireEvent()
{
if (MyEvent != null)
MyEvent();
}
}
class MainClass
{
static void MyMethod()
{
Console.WriteLine(“This is called by event”);
}
static void Main()
{
EventClass e = new EventClass();
e.MyEvent+=new MyDel(MyMethod);
e.MyEvent+=new MyDel(UrMethod);
e.FireEvent();
}
static void UrMethod()
{
Console.WriteLine(“This is ur method”);
}
}
}
Program26:
using System;
namespace AlarmProject
{
public class AlarmEventArgs : EventArgs
{
public readonly bool snoozepressed;
public readonly int nrings;
public AlarmEventArgs(bool snoozepressed,int nrings)
{
this.snoozepressed = snoozepressed;
this.nrings = nrings;
}
public bool SnoozePressed
{
get
{
return snoozepressed;
}
}
public int NRings
{
get
{
return nrings;
}
}
public string AlarmText
{
get
{
if (!snoozepressed)
{
return “WakeUp!!!”;
}
else
{
return “SnoozeTime Up.WakeUP!!\n”;
}
}
}
}
public delegate void AlarmEventHandler(object sender,AlarmEventArgs e);
class AlarmClass
{
public event AlarmEventHandler AlarmEvent;
public void OnAlarm(AlarmEventArgs e)
{
if (AlarmEvent != null)
AlarmEvent(this, e);
}
private bool snoozepressed = false;
private bool stop = false;
private int nrings = 0;
public bool SnoozePressed
{
get
{
return snoozepressed;
}
set
{
snoozepressed = value;
}
}
public bool Stop
{
get
{
return stop;
}
set
{
stop = value;
}
}
public void Start()
{
for (; ; )
{
nrings++;
if (stop)
return;
else if (snoozepressed)
{
System.Threading.Thread.Sleep(1000);
AlarmEventArgs e = new AlarmEventArgs(snoozepressed,nrings );
OnAlarm(e);
}
else
{
System.Threading.Thread.Sleep(300);
AlarmEventArgs e = new AlarmEventArgs(snoozepressed ,nrings );
OnAlarm(e);
}
}
}
}
public class Wakeup
{
public void Call(object sender, AlarmEventArgs e)
{
Console.WriteLine(e.AlarmText + “\n”);
if (!e.snoozepressed)
{
if (e.NRings % 10 == 0)
{
Console.WriteLine(“Let the AlarmRing(Press y)”);
Console.WriteLine(“Press Snooze (press n)”);
Console.WriteLine(“Exit Alarm (press Q)”);
string input =Console.ReadLine();
if (input.Equals(“y”) || input.Equals(“Y”))
{
return;
}
else if (input.Equals(“n”) || input.Equals(“N”))
{
((AlarmClass)sender).SnoozePressed = true;
return;
}
else
{
((AlarmClass)sender).Stop = true; return;
}
}
}
else
{
Console.WriteLine(“Let the Alarm Ring (Press y)”);
Console.WriteLine(“Exit Alarm (press q)”);
string input = Console.ReadLine();
if (input.Equals(“y”) || input.Equals(“Y”))
{
return;
}
else
{
((AlarmClass)sender).Stop = true; return;
}
}
}
}
class MainClass
{
static void Main()
{
Wakeup w = new Wakeup();
AlarmClass a = new AlarmClass();
a.AlarmEvent += new AlarmEventHandler(w.Call);
a.Start();
}
}
}
Program27:
using System;
using System.Threading;
namespace ThreadDemo1
{
class Demo
{
public void myFucntion()
{
for (int i = 0; i < 50; i++)
Console.WriteLine(“Myfunction” + i);
}
public void UrFunction()
{
for (int i = 0; i < 50; i++)
Console.WriteLine(“urFunction” + i);
}
}
class MainClass
{
static void Main()
{
Demo d = new Demo();
//d.myFucntion();
//d.UrFunction();
Thread t1 = new Thread(new ThreadStart(d.myFucntion));
Thread t2 = new Thread(new ThreadStart(d.UrFunction));
t1.Start(); t2.Start();
}
}
}
Program28:
using System;
using System.Threading;
namespace ThreadDemo2
{
class MyClass
{
private string str;
public MyClass(string str)
{
this.str = str;
}
public void MyFun()
{
for (int i = 0; i <= 200; i++)
Console.Write(str);
}
}
class MainClass
{
public static void Main()
{
// MyClass m1 = new MyClass(“A”);
// MyClass m2 = new MyClass(“B”);
// Thread t1 = new Thread(new ThreadStart(m1.MyFun));
// Thread t2 = new Thread(new ThreadStart(m2.MyFun));
// t1.Start();
// t2.Start();
Demo d = new Demo();
Thread t3 = new Thread(new ParameterizedThreadStart(d.MyFun));
Thread t4 = new Thread(new ParameterizedThreadStart(d.MyFun));
t3.Start(“C”);
t4.Start(“D”);
}
}
class Demo
{
public void MyFun(object obj)
{
for (int i = 0; i < 300; i++)
Console.Write(obj.ToString());
}
}
}
Program28:
using System;
using System.Threading;
namespace ThreadDemo2
{
class MyClass
{
private string str;
public MyClass(string str)
{
this.str = str;
}
public void MyFun()
{
for (int i = 0; i <= 200; i++)
Console.Write(str);
}
}
class MainClass
{
public static void Main()
{
// MyClass m1 = new MyClass(“A”);
// MyClass m2 = new MyClass(“B”);
// Thread t1 = new Thread(new ThreadStart(m1.MyFun));
// Thread t2 = new Thread(new ThreadStart(m2.MyFun));
// t1.Start();
// t2.Start();
Demo d = new Demo();
Thread t3 = new Thread(new ParameterizedThreadStart(d.MyFun));
Thread t4 = new Thread(new ParameterizedThreadStart(d.MyFun));
t3.Start(“C”);
t4.Start(“D”);
}
}
class Demo
{
public void MyFun(object obj)
{
for (int i = 0; i < 300; i++)
Console.Write(obj.ToString());
}
}
}
Program29:
using System;
using System.Threading;
namespace threaddemo3
{
class MyClass
{
public void TargetA()
{
for (int i = 0; i <= 15; i++)
{
Console.WriteLine(Thread.CurrentThread.Name + “:” + i);
Thread.Sleep(1000);
}
}
}
class MainClass
{
static void Main()
{
MyClass c=new MyClass();
Thread t1 = new Thread(new ThreadStart(c.TargetA));
Thread t2 = new Thread(new ThreadStart(c.TargetA));
Thread t3 = new Thread(new ThreadStart(c.TargetA));
t1.Name = “one”;
t2.Name = “two”;
t3.Name = “Three”;
t1.Start(); t2.Start(); t3.Start();
}
}
}
Program30:
using System;
using System.Threading;
namespace ThreadDemo4
{
class Test
{
public static void Run1()
{
for (int i = 1; i <= 25; i++)
Console.WriteLine(“{0} * 5 ={1}”, i, i * 5);
}
public static void Run2()
{
for (int i = 1; i <= 25; i++)
Console.WriteLine(“{0} * 8 ={1}”, i, i * 8);
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(“Starting of Main”);
Thread t1 = new Thread(new ThreadStart(Test.Run1));
Thread t2 = new Thread(new ThreadStart(Test.Run2));
t1.Start();
t2.Start(); t1.Join();
t2.Join();
Console.WriteLine(“End of Main method”);
}
}
}
Program31:
using System;
using System.Threading;
namespace ThreadDemo5
{
class Test
{
public void TargetA()
{
for (int i = 0; i <= 25; i++)
{
Console.WriteLine(Thread.CurrentThread.Name + “:” + i);
}
}
}
class MainClass
{
static void Main()
{
Test c = new Test();
Thread t1 = new Thread(new ThreadStart(c.TargetA));
Thread t2 = new Thread(new ThreadStart(c.TargetA));
Thread t3 = new Thread(new ThreadStart(c.TargetA));
t1.Name = “one”;
t2.Name = “two”;
t3.Name = “Three”;
t1.Priority = ThreadPriority.Lowest;
t3.Priority = ThreadPriority.BelowNormal;
t2.Priority = ThreadPriority.Highest;
t1.Start(); t2.Start(); t3.Start();
}
}
}
Program32:
using System;
using System.Threading;
namespace Threaddemo6
{
class Test
{
public static void TargetA()
{
for (int i = 0; i <= 15; i++)
Console.WriteLine(“A:\t” + i);
}
public static void TargetB()
{
for (int i = 35; i > 0; i–)
Console.WriteLine(“B:\t” + i);
}
}
class MainClass
{
static void Main()
{
Thread t1 = new Thread(new ThreadStart(Test.TargetA));
Thread t2 = new Thread(new ThreadStart(Test.TargetB));
t2.IsBackground = true;
t1.Start(); t2.Start();
}
}
}
Program33:
using System;
using System.Threading;
namespace Sync
{
class Demo
{
public void MyMethod()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(“Shared::” + Thread.CurrentThread.Name + “:\t” + i);
Thread.Sleep(200);
}
lock (this)
{
for (int i = 0; i <= 10; i++)
{
Console.WriteLine(Thread.CurrentThread.Name + “:\t” + i);
Thread.Sleep(200);
}
}
}
}
class MainClass
{
public static void Main()
{
Demo d = new Demo();
Thread t1 = new Thread(new ThreadStart(d.MyMethod));
Thread t2 = new Thread(new ThreadStart(d.MyMethod));
t1.Name = “one”; t2.Name = “two”;
t1.Start(); t2.Start();
}
}
}
Program34:
using System;
using System.Threading;
namespace mutexDemo
{
class Demo
{
Mutex m = new Mutex();
public void display()
{
m.WaitOne();
for (int i = 0; i <= 100; i++)
Console.WriteLine(Thread.CurrentThread.Name +“\t:” + i);
m.ReleaseMutex();
}
}
class MainClass
{
public static void Main()
{
Demo d = new Demo();
Thread t1 = new Thread(new ThreadStart(d.display));
Thread t2 = new Thread(new ThreadStart(d.display));
t1.Name = “one”; t2.Name = “two”;
t1.Start(); t2.Start();
}
}
}