Sie sind auf Seite 1von 70

DKES- SCHOOL OF COMPUTER SCIENCE

C# Programming
Practical File
Ketan Rajpal
3rd Semester

Paper Code: MCA 255 Student Name: Ketan Rajpal


Paper Title: C# Programming Enrollment Number: 04516204410
Paper ID: 044255 College Name: School of Computer Science
Session: August - December 2011 University Name: Guru Gobind Singh Indraprastha University
C# Programming Ketan Rajpal Practical File

Index

S.no Topic Page no


1. Write a program to print size of all value types.

2. Create a structure name with member variables firstname, middlename and lastname. The 5
structure contains a parameterized constructor to initialize the name. Create a class
employee with member variables:
Struct variable of type name
Designation of string type
Salary of decimal type
Input all the values from the user in instance method read and display all the values in the
instance method write.

3. Create a class called myvalue with a data member x of type object. Now show the usage of
the following methods in this class:
Equal()
Gettype()
Gethashcode()
Tostring()

4. Write a program to explain the concept of boxing and unboxing

5. Write a program that reads a 1-d array of integers. Using binary search, find whether a
number x is found in the array or not. Input x from user.

6. Write a program that reads a 2-d jagged array of integers. Use linear search to find a given
number in the array.

7. Write a program for sorting a 1-d array of strings, using:


1) insertion sort 2)selection sort

8. Write a program to implement the nested class concept.

9. Write a program that defines a class student. There are 2 data member name and rollno,
with the respective properties associated with them. Also, there is an auto-implemented
boolean property status to indicate student is pass or fail.

10. Write a program to write three methods in a class. Use concept of multicasting in delegates,
to invoke the method chain

11. Write a program to define a class. The class has the following member variables:
The class should contain:
Non parameterized constructor
Parameterized constructor
Static constructor
Indexer
Overload = = operator to compare 2 students

12. Write a program that implements a fraction class that has two integral data members
numerator and denominator. Define the following methods:
Method to calculate lcm
Method to calculate gcd
Conversion function from int to fraction
Conversion function from fraction to int

2|Page
C# Programming Ketan Rajpal Practical File

Overload operators + - * = = != < >


Overload tostring() method of object class to display fraction in the format num/denom.

13. Write a program to swrite a program two integers in two ways:


Passing parameters by reference
Passing parameters by value

14. Write a program to implement all the properties and methods of string class and datetime
class

15. Create 2 assemblies one shared (using gacutil) and one private. Refer these assemblies in a
console application.

16. Write a program in c# to perform following tasks:


Copy data from two text files to a third file
Calculate length of the destination file
Handle exceptions while opening a file, reading or writing a file and wherever required.

17. Create a window form application such that when the mouse button is clicked and moved in
the form, a line is drawn corresponding to the mouse movement. Using a mouse down event,
identify whether the right or left mouse button is clicked and display the appropriate
message in the message box. For eg. right mouse button clicked!

18. Create a window form application to generate a tic-tac-toe program.

19. Create a window form application to design and implement a calculator.

20. Create a window form application to design the following form[make use of delegates and
events]:

Write code to add different colors name to the list box the item should appear in the list
box in the alphabetically sorted order.
Add button, adds the text into the list box that was typed into the textbox it then clears
the textbox. The current no. Of list box items should be displayed on the label. The focus
is again set back to the textbox for adding new item.
Remove button remove the selected item from the listbox and label that displays the
item is decremented if none of the item is selected then remove button is disabled..
Clear button clears all the items in the listbox. Then disables the remove command
button and label that display the list item becomes zero.

21. Write a program in c++ to define an interface ishape that can describe any simple shape such
as square, circle or rectangle. The size of all these shapes can be reduced to a single
dimension. Create classes for each of these three shapes, that implement ishape interface.
Create an abstract function in the ishape interface that returns area of each shape. Now,
create an array of heterogeneous shapes and display area of shape stored in the array.

22. Create a student class, with attribute name and rollno. Derive a class exams from it with
attribute int [] marks, which is an array of marks in 5 subjects. Derive a class result from it,
which calculates total marks and prints it. There are read and write methods in each of the
classes. Use concept of virtual keyword. Also, use new keyword to provide a new
implementation of the read method in the result class.

3|Page
C# Programming Ketan Rajpal Practical File

23. Create an application that defines a user-defined exception class negativenumexception.


When user enters a positive numeric value, its square root is calculated. If the negative value
is entered, then negativenumexception exception is thrown.

24. Write a program to raise an exception whenever 2 numbers are divided, in order to handle
divide by zero exception.

25. Write a program in c# to implement a user-defined generic mehod.

26. Write a program using generic collection list<t> to do the following:


Create an employee class
Store 10 employee objects in list<t>
Using ienumeratot<t>, iterate through the list collection of employee objects.
Display the first and last object of the list.

27. Write a program using dicionary<k,t> to do the following:


Implement a telephone directory of names and phone numbers
Search the telephone number, given name as input, from the above directory.

28. Write a console application to check whether a given number is even or odd in a list<t> of
integers. Return the list of even numbers and odd numbers present in the given list. Use
lambda expression to create even function and anonymous delegate to create function for
checking odd numbers.

29. Write a program in c# to implement a generic delegate type.

30. Implement a simple paint application using gdi+.

31. Implement a complete wpf application.

32. Write a console application that creates a customer class and stores student objects in a
list<t>. The customer class has three properties: firstname, lastname, and emailaddress. It
overrides the object.tostring( ) method to provide a string representation of its instances.
Write a linq query to retrieve all customer objects whose first name is donna from the
customer list, and then update firstname of the fourth customer in the list as donna.

33. Write a console program in c# to demonstrate the use of anonymous types in a linq join
query.

4|Page
C# Programming Ketan Rajpal Practical File

Purpose of Program: Create a structure Name with member variables firstname,


middlename and lastname. The structure contains a parametrized constructor to initialize
the name. Create a class Employee with member variables:

1) struct variable of type Name

2) Designation of string type

3) Salary of decimal type

Input all the values from the user in instance method read and display all the values in the

instance method write.

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

namespace ConsoleApplication17
{
public struct Name
{
public string FName;
public string MName;
public string LName;
public Name(string fname, string mname, string lname)
{
FName = fname;
MName = mname;
LName = lname;
}
}
class Employee
{
Name StructOb = new Name("Harshit", "Gupta", "Rocks");
string desig;
decimal sal;
public void read()
{
Console.WriteLine("\nEnter designation...");
desig = Console.ReadLine();
Console.WriteLine("\nEnter salary...");
sal = Int32.Parse(Console.ReadLine());
}

public void write()


{
Console.WriteLine("\n DETAILS OF EMPLOYEE");
Console.WriteLine("\n First Name:-{0}", StructOb.FName);
Console.WriteLine("\n Middle Name:-{0}", StructOb.MName);
Console.WriteLine("\n Last Name:-{0}", StructOb.LName);
Console.WriteLine("\n Designation is:-{0}", desig);
Console.WriteLine("\n Salary:-{0}", sal);
}
}

class Program
{
static void Main(string[] args)
{
Employee e1 = new Employee();
e1.read();
e1.write();

5|Page
C# Programming Ketan Rajpal Practical File
Console.ReadLine();
}
}
}

Output:

Enter designation...
Manager

Enter salary...
70000
DETAILS OF EMPLOYEE
First Name:-Harshit
Middle Name:-Gupta
Last Name:-Rocks
Designation is:-Manager
Salary:-70000

6|Page
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program that defines a class Student. There are 2 data
member name and rollno, with the respective properties associated with them. Also, there is
an auto-implemented Boolean property status to indicate student is pass or fail.

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

namespace ConsoleApplication38
{
class Student
{
string name;
int roll;
int marks;
public string stuname
{
get
{
return name;
}
set
{
name = value;
}
}
public int sturoll
{
get
{
return roll;
}
set
{
roll = value;
}
}
public int stumarks
{
get{
return marks;
}
set{
marks=value;
}
}
public Boolean status { get; set; }
}
class Program
{
static void Main(string[] args)
{
Student s1 = new Student();
Console.Write("enter name: ");
s1.stuname = Console.ReadLine();
Console.Write("enter roll :");
s1.sturoll = Int32.Parse (Console.ReadLine().ToString());
Console.WriteLine("enter marks :");
s1.stumarks = Int32.Parse(Console.ReadLine().ToString());
string str1 = s1.stuname;
int r = s1.sturoll;
int m = s1.stumarks;
s1.status = true;
Console.WriteLine("STUDENT NAME IS {0}\n", str1);

7|Page
C# Programming Ketan Rajpal Practical File
Console.WriteLine("STUDENT ROLL NUMBER IS {0}\n", r);
Console.WriteLine("marks is {0}", m);
Boolean state = s1.status;
if (m >=50)
Console.WriteLine("RESULT OF {0} IS PASS...!", s1.stuname);
else
Console.WriteLine("RESULT OF {0} IS FAIL...!", s1.stuname);
Console.ReadLine();
}
}
}

Output:

enter name: harshit


enter roll :4410
enter marks :
89
STUDENT NAME IS harshit
STUDENT ROLL NUMBER IS 4410
marks is 89
RESULT OF harshit IS PASS...!

8|Page
C# Programming Ketan Rajpal Practical File

Purpose of program: Write a program to write three methods in a class. Use concept of

multicasting in delegates, to invoke the method chain.

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

namespace ConsoleApplication16
{
delegate void Mydlg();

class Multicast
{
public void display()
{
Console.WriteLine("In display() method.");
Console.WriteLine("Implementing Multicast delegates.");
}

public void print()


{
Console.WriteLine("In print() method.");
Console.WriteLine("Implementing Multicast delegates.");
}
public void add()
{
int num1, num2;
Console.WriteLine("In add() method.");
Console.WriteLine("Enter 2 numbers..");
num1 = Int32.Parse(Console.ReadLine());
num2 = Int32.Parse(Console.ReadLine());
Console.WriteLine("Addition=" + (num1 + num2));
}
}

class Program
{
static void Main(string[] args)
{
Multicast m = new Multicast();
Mydlg dlg;
Mydlg d1 = new Mydlg(m.display);
Mydlg d2 = new Mydlg(m.print);
Mydlg d3 = new Mydlg(m.add);
dlg = d1 + d3;
dlg();
dlg = d1 + d2;
dlg();
dlg = d1 - d3;
dlg();
Console.ReadLine();
}
}
}

9|Page
C# Programming Ketan Rajpal Practical File

Output:

In display() method.
Implementing Multicast delegates.

In add() method.
Enter 2 numbers..
45
55
Addition=100

In display() method.
Implementing Multicast delegates.

In print() method.
Implementing Multicast delegates.

In display() method.
Implementing Multicast delegates.

10 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Create a class called MyValue with a data member x of type Object.

Now show the usage of the following methods in this class:

1) Equal()

2) GetType()

3) GetHashCode()

4) ToString()

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

namespace ConsoleApplication43
{

class Dev
{
public Object x;
public Dev(Object y)
{
x = y;
}

}
class Program
{
static void Main(string[] args)
{
Object x=new Object() ;
Dev d1 = new Dev(x);
System.Console.WriteLine("IS d1.x EQUALS TO x="+ d1.Equals(x));
System.Console.WriteLine("IS d1 EQUALS TO x=" + d1.Equals(x));
System.Console.WriteLine("IS x EQUALS TO d1.x=" + x.Equals(d1.x));
System.Console.WriteLine("HASH CODE OF MYVALUE OBJECT d1 IS:" + d1.GetHashCode());
System.Console.WriteLine("HASH CODE OF MYVALUE OBJECT d1.x IS:" + d1.x.GetHashCode());
System.Console.WriteLine("HASH CODE OF x IS:" + x.GetHashCode());
System.Console.WriteLine("TYPE OF Dev OBJECT d1 IS:" + d1.GetType() + "\t\t");
System.Console.WriteLine("CONVERTING Dev OBJECT d1 INTO STRING:" +d1.ToString() +
"\t\t");

System.Console.ReadLine();

}
}
}

Output:

IS d1.x EQUALS TO x=False


IS d1 EQUALS TO x=False
IS x EQUALS TO d1.x=True
HASH CODE OF MYVALUE OBJECT d1 IS:46104728
HASH CODE OF MYVALUE OBJECT d1.x IS:12289376
HASH CODE OF x IS:12289376
TYPE OF Dev OBJECT d1 IS:ConsoleApplication43.Dev
CONVERTING Dev OBJECT d1 INTO STRING:ConsoleApplication43.Dev

11 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program to implement the Nested class concept.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication28
{
public class ABC
{
public void sum()
{
int i = 10, j = 20;
int s;
s = i + j;
Console.WriteLine("after adding value will be " + s);
}
internal class A
{
public void mul()
{
int k = 50;
int l = 5;
int m;
m = k * l;
Console.WriteLine("after multiplying in internal class " + m);
}
}
}
class Program
{
static void Main(string[] args)
{
ABC a = new ABC();
a.sum();
ABC.A b = new ABC.A();
b.mul();
Console.ReadLine();
}
}
}

Output:

after adding value will be 30


after multiplying in internal class 250

12 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program to define a class . The class has the following member
variables:
The class should contain:
1) Non parameterized constructor
2) Parameterized constructor
3) Static constructor
4) Indexer
5) Overload = = operator to compare 2 students

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

namespace ConsoleApplication45
{
class Student
{

public string name;


public int rollno;
public int size;
public int[] marks;
public static string name1;
public static int rollno1;
public static int[] marks1 = { 90, 98, 93, 50 };
public Student()
{
size = 3;
marks = new int[size];
name = "harshit";
rollno = 5050;
}
public Student(string n, int r, int size)
{
marks = new int[size];
name = n;
rollno = r;
}
static Student()
{
name1 = "harsh";
rollno1 = 40;

}
public int this[int index]
{
get
{
return marks[index];

}
set
{
marks[index] = value;
}
}

public static bool operator ==(Student s1, Student s2)


{

13 | P a g e
C# Programming Ketan Rajpal Practical File
if (s1.name.Equals(s2.name) && s1.rollno == s2.rollno && s1.Equals(s2))
return true;
else
return false;

public static bool operator !=(Student s1, Student s2)


{
if (!s1.name.Equals(s2.name) && s1.rollno != s2.rollno)

return true;
else
return false;

}
public void display()
{
Console.WriteLine(" student name: " + name);
Console.WriteLine(" student rollno: " + rollno);
int sum = 0;
for (int i = 0; i < marks.Length; i++)
{
sum = sum + marks[i];
}
System.Console.WriteLine("sum: " + sum);
}
}

class Program
{
static void Main(string[] args)
{

Student s1 = new Student();


Student s2 = new Student();
s1[0] = 65;
s1[1] = 76;
s1[2] = 98;

s2[0] = 65;
s2[1] = 76;
s2[2] = 98;

Student s3 = new Student("satish", 50, 4);


s3[0] = 90;
s3[1] = 87;
s3[2] = 80;
s3[3] = 99;

s1.display();
s2.display();
s3.display();

Console.WriteLine(" student name: " + Student.name1);


Console.WriteLine(" student rollno: " + Student.rollno1);
int sum = 0;
for (int i = 0; i < Student.marks1.Length; i++)
{
sum = sum + Student.marks1[i];
}
System.Console.WriteLine("sum: " + sum);

Student s4 = s3;
if (s1 == s2)
Console.WriteLine("both students are same ");

14 | P a g e
C# Programming Ketan Rajpal Practical File
else
Console.WriteLine("both student are different ");

if (s3 == s4)
Console.WriteLine("both students are same ");
else
Console.WriteLine("both student are different ");
System.Console.ReadLine();

}
}
}

Output:

student name: harshit


student rollno: 5050
sum: 239
student name: harshit
student rollno: 5050
sum: 239
student name: ketan
student rollno: 50
sum: 356
student name: harshit
student rollno: 40
sum: 331
both student are different
both students are same

15 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program to implement all the properties and methods of
String class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication34
{
class Str
{
static void Main(string[] args)
{
string s2 = "Gupta";
string a="Mr. ";
StringBuilder s1 = new StringBuilder("Harshit");
s1.Append(s2);
Console.WriteLine(s1.ToString());
s1.Insert(0, a);
Console.WriteLine(s1);
s1.Remove(5, 3);

Console.WriteLine(s1);
s1.Replace("ran", "Devesh");
Console.WriteLine(s1);
Console.WriteLine("length of string" + s1.Length);
Console.WriteLine("capacity is " + s1.Capacity);
s1.Length = 7;
Console.WriteLine(s1.ToString());

Console.ReadLine();
}
}
}

Output:

HarshitGupta
Mr. HarshitGupta
Mr. ran kumarjha
Mr. Devesh kumarjha
length of string19
capacity is 23
Mr. Dev

16 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Create 2 assemblies one shared(Using GACUTIL) and one private. Refer
these assemblies in a console application.

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

namespace Dev
{
public class Ros
{
public void disp()
{
Console.WriteLine("hello roshan how are you");
}
}
}

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

namespace ConsoleApplication41
{
class Program
{
static void Main(string[] args)
{
Dev.Ros ob = new Dev.Ros();
ob.disp();
Console.ReadKey();

}
}
}

Steps

Setting environment for using Microsoft Visual Studio 2010 x86 tools.
C:\Program Files\Microsoft Visual Studio 10.0\VC>cd\
C:\>cd C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\P
rojects\Dev
C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects
\Dev>sn -k hello.snk
Microsoft (R) .NET Framework Strong Name Utility Version 4.0.30319.1
Copyright (c) Microsoft Corporation. All rights reserved.
Key pair written to hello.snk
C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects
\Dev>sn -k hello.snk
Microsoft (R) .NET Framework Strong Name Utility Version 4.0.30319.1
Copyright (c) Microsoft Corporation. All rights reserved.
Key pair written to hello.snk
C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects
\Dev>cd\
C:\>cd C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\P
rojects\Dev\Dev\bin\Debug
C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects
\Dev\Dev\bin\Debug>gacutil /i Dev.dll
Microsoft (R) .NET Global Assembly Cache Utility. Version 4.0.30319.1
Copyright (c) Microsoft Corporation. All rights reserved.
Assembly successfully added to the cache
C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects
\Dev\Dev\bin\Debug>

17 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program to print size of all value types.

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

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
int size1 = sizeof(int);
int size2 = sizeof(decimal);
int size3 = sizeof(char);
int size4 = sizeof(bool);
int size5 = sizeof(byte);
int size6 = sizeof(Int16);
int size7 = sizeof(Int32);
int size8 = sizeof(Int64);

Console.WriteLine("Size of Integer:{0}\nSize of Decimal:{1}\nSize of


Character:{2}\nSize of Boolean:{3}\nSize of Byte:{4}\nSize of Short
Integer(Int16):{5}\nSize of Integer(Int32):{6}\nSize of Long Integer(Int64):{7}\n",
size1, size2, size3, size4, size5, size6, size7, size8);
Console.ReadLine();

}
}
}

Output:

Size of Integer:4
Size of Decimal:16
Size of Character:2
Size of Boolean:1
Size of Byte:1
Size of Short Integer(Int16):2
Size of Integer(Int32):4
Size of Long Integer(Int64):8

18 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program to explain the concept of Boxing and UnBoxing.

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

namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
int myInt1 = 10;
Console.WriteLine("myInt1.ToString() = " + myInt1.ToString());
Console.WriteLine("myInt1.GetType() = " + myInt1.GetType());

int myInt2 = 10;


object myObject = myInt2;
Console.WriteLine("myInt2 = " + myInt2);
Console.WriteLine("myObject = " + myObject);

int myInt3 = (int)myObject;


Console.WriteLine("myInt3 = " + myInt3);
Console.ReadLine();
}
}
}

Output:

myInt1.ToString() = 10
myInt1.GetType() = System.Int32
myInt2 = 10
myObject = 10
myInt3 = 10

19 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program that reads a 1-D array of integers. Using binary

search, find whether a number x is found in the array or not. Input s from user.

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{

int[] a = new int[200];


int big, end, mid;
Console.WriteLine("Program for Linear Search");
Console.WriteLine("Enter number of elements of searching array?");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(" ");
Console.WriteLine("\nEnter integer searching array elements \n");
for (int i = 0; i < n; i++)
{
a[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Enter element to search:\n");
int s = Convert.ToInt32(Console.ReadLine());
for (int pass = 1; pass <= n - 1; pass++)
{
for (int i = 1; i <= n - 1; i++)
{
int temp = a[i];
for (int j = i - 1; j >= 0 && a[j] > temp; j--)
{
a[j + 1] = a[j];
a[j] = temp;
}
}
}

big=0;
end=n;
mid=(big+end)/2;
while(big<end)
{
mid = (big + end) / 2;
if (a[mid] == s)
{
Console.WriteLine("Element {0} is found ", s);
break;
}
else if (s < a[mid])
{
end = mid - 1;

}
else
{
big = mid + 1;
}
}
Console.ReadLine();
}
}
}

20 | P a g e
C# Programming Ketan Rajpal Practical File

Output:

Program for Linear Search


Enter number of elements of searching array?
5

Enter integer searching array elements


1
5
2
6
4
Enter element to search:
4
Element 4 is found

21 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program that reads a 2-D jagged array of integers. Use linear

search to find a given number in the array.

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
int[][] jagged = new int[3][];
int ele;
jagged[0] = new int[2];
jagged[1] = new int[1];
jagged[2] = new int[3];

Console.WriteLine("Enter the elements of the array:");


for (int i = 0; i < jagged.Length; i++)
{
int[] innerArray = jagged[i];
for (int a = 0; a < innerArray.Length; a++)
{
Console.Write("Enter the element for [{0}][{1}]:", i, a);
innerArray[a] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine();
}
Console.WriteLine("Enter the number you want to search in the array:");
ele = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < jagged.Length; i++)
{
int[] innerArray = jagged[i];
for (int a = 0; a < innerArray.Length; a++)
{
if (innerArray[a] == ele)
Console.WriteLine("Element {0} is found in the array:",
innerArray[a]);
else
Console.WriteLine("Element {0} is not found in the array");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}

Output:

Enter the elements of the array:


Enter the element for [0][0]:1
Enter the element for [0][1]:2
Enter the element for [1][0]:3
Enter the element for [2][0]:4
Enter the element for [2][1]:5
Enter the element for [2][2]:6
Enter the number you want to search in the array:
5
Element 5 is found in the array:

22 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program to implement Insertion sort.

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

namespace ConsoleApplication7
{
class Program
{
public void arrayAccept(int[] array, int n)
{
Console.WriteLine("\nEnter the numbers:");
for (int a = 0; a < n; a++)
array[a] = Convert.ToInt32(Console.ReadLine());
}
public void insertionSort(int[] array, int n)
{
for (int pass = 1; pass <= n - 1; pass++)
{
for (int i = 1; i <= n - 1; i++)
{
int temp = array[i];
for (int j = i - 1; j >= 0 && array[j] > temp; j--)
{
array[j + 1] = array[j];
array[j] = temp;
}
}
}
}
public void displayArray(int[] array, int n)
{
Console.WriteLine("\nThe sorted array elements are:");
for (int a = 0; a < n; a++)
Console.WriteLine(array[a]);
}
static void Main(string[] args)
{
Program p = new Program();
Console.WriteLine("Enter the number of elements in the array:");
int num = Convert.ToInt32(Console.ReadLine());
int[] array = new int[num];
p.arrayAccept(array, num);
p.insertionSort(array, num);
p.displayArray(array, num);
Console.ReadLine();
}
}
}

Output:

Enter the number of elements in the array:


5

Enter the numbers:


1 23 11 58 96

The sorted array elements are:


1 11 23 58 96

23 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program to implement Selection Sort.

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication8
{
class Program
{
private int[] a = new int[100];

private int x;

public void sortArray()


{
int i, j;
int min, temp;

for (i = 0; i < x - 1; i++)


{
min = i;

for (j = i + 1; j < x; j++)


{
if (a[j] < a[min])
{
min = j;
}
}
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}

public static void Main()


{
Program mySort = new Program();
Console.Write("Number of elements in the array (less than 100) : ");
string s = Console.ReadLine();
mySort.x = Int32.Parse(s);
Console.WriteLine("");
Console.WriteLine(" Enter array elements ");
for (int i = 0; i < mySort.x; i++)
{
Console.Write("<{0}> ", i + 1);
string s1 = Console.ReadLine();
mySort.a[i] = Int32.Parse(s1);
}
mySort.sortArray();

Console.WriteLine("");
Console.WriteLine(" Sorted array elements ");

for (int j = 0; j < mySort.x; j++)


{
Console.WriteLine(mySort.a[j]);
}

Console.Read();
}
}
}

24 | P a g e
C# Programming Ketan Rajpal Practical File

Output:

Number of elements in the array (less than 100) : 5


Enter array elements
<1> 5
<2> 68
<3> 94
<4> 11
<5> 25
Sorted array elements
5
11
25
68
94
Press Return to exit.

25 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program to Write a program two integers in two ways:

1) Passing parameters by reference

2) Passing parameters by value

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication9
{
class Program
{
public static void PassByValue(int input)
{
input = input + 10;
Console.WriteLine("In function PassByValue: input = {0}", input);
}
public static void PassByRef(ref int input)
{
input = input + 50;
Console.WriteLine("In function PassByRef: input = {0}", input);
}
public static void PassByOut(out int input)
{
input = 75;
Console.WriteLine("In function PassByOut: input = {0}", input);
}
class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public static void PassingObjectsByValue(Employee emp)
{
emp.Name = "PassingObjectsByValue";
Console.WriteLine("In function PassingObjectsByValue: employee name = {0}",
emp.Name);
}
public static void PassingObjectsByRef(ref Employee emp)
{
emp.Name = "PassingObjectsByRef";
Console.WriteLine("In function PassingObjectsByRef: employee name = {0}",
emp.Name);
}
static void Main(string[] args)
{
int input = 5;
Console.WriteLine("In Main: input = {0}", input);
PassByValue(input);
Console.WriteLine("In Main after calling PassByValue: input = {0}\n",
input);
PassByRef(ref input);
Console.WriteLine("In Main after calling PassByRef: input = {0}\n", input);
PassByOut(out input);
Console.WriteLine("In Main after calling PassByOut: input = {0}\n", input);
Employee emp = new Employee();
emp.Id=5;
emp.Name="harshit";
Console.WriteLine("In Main: Employee Name = {0}", emp.Name);
PassingObjectsByValue(emp);
Console.WriteLine("In Main after calling PassingObjectsByValue: Employee
Name = {0}\n", emp.Name);
PassingObjectsByRef(ref emp);
Console.WriteLine("In Main after calling PassingObjectsByRef: Employee Name
= {0}\n", emp.Name);
} } }

26 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program to implement all the properties and methods of

String class.

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication10
{
class Program
{
private string myName = "N/A";
private int myAge = 0;

public string Name


{
get
{
return myName;
}
set
{
myName = value;
}
}

public int Age


{
get
{
return myAge;
}
set
{
myAge = value;
}
}

public override string ToString()


{
return "Name = " + Name + ", Age = " + Age;
}

public static void Main()


{
Console.WriteLine("Simple Properties");

Program person = new Program();

Console.WriteLine("Person details - {0}", person);

person.Name = "Joe";
person.Age = 99;
Console.WriteLine("Person details - {0}", person);

person.Age += 1;
Console.WriteLine("Person details - {0}", person);
Console.ReadLine();

}
}
}

27 | P a g e
C# Programming Ketan Rajpal Practical File

Output:

Simple Properties
Person details - Name = N/A, Age = 0
Person details - Name = Joe, Age = 99
Person details - Name = Joe, Age = 100

28 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program to implement all the properties and methods of

DateTime class.

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

namespace ConsoleApplication11
{
class Program
{
static void Main(string[] args)
{
DateTime CurrTime = DateTime.Now;
Console.WriteLine("DateTime display listing specifier and result:\n");
Console.WriteLine("d = {0:d}", CurrTime);
Console.WriteLine("D = {0:D}", CurrTime);
Console.WriteLine("f = {0:f}", CurrTime);
Console.WriteLine("F = {0:F}", CurrTime);
Console.WriteLine("g = {0:g}", CurrTime);
Console.WriteLine("G = {0:G}", CurrTime);
Console.WriteLine("M = {0:M}", CurrTime); Console.WriteLine("R
= {0:R}", CurrTime);
Console.WriteLine("s = {0:s}", CurrTime); Console.WriteLine("t
= {0:t}", CurrTime);
Console.WriteLine("T = {0:T}", CurrTime);
Console.WriteLine("u = {0:u}", CurrTime);
Console.WriteLine("U = {0:U}", CurrTime);
Console.WriteLine("Y = {0:Y}", CurrTime);
Console.WriteLine();
Console.WriteLine("DateTime.Month = " + CurrTime.Month);
Console.WriteLine("DateTime.DayOfWeek = " + CurrTime.DayOfWeek);
Console.WriteLine("DateTime.TimeOfDay = " + CurrTime.TimeOfDay);
Console.WriteLine("DateTime.Ticks = " + CurrTime.Ticks);
Console.Read();
}
}
}

Output:

DateTime display listing specifier and result:


d = 9/25/2011
D = Sunday, September 25, 2011
f = Sunday, September 25, 2011 10:21 PM
F = Sunday, September 25, 2011 10:21:40 PM
g = 9/25/2011 10:21 PM
G = 9/25/2011 10:21:40 PM
M = September 25
R = Sun, 25 Sep 2011 22:21:40 GMT
s = 2011-09-25T22:21:40
t = 10:21 PM
T = 10:21:40 PM
u = 2011-09-25 22:21:40Z
U = Sunday, September 25, 2011 4:51:40 PM
Y = September, 2011

DateTime.Month = 9
DateTime.DayOfWeek = Sunday
DateTime.TimeOfDay = 22:21:40.2500000
DateTime.Ticks = 634525861002500000

29 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program, to write three methods in a class. Use concept of

multicasting in delegates, to invoke the method chain.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplication12
{
class Program
{
public delegate void LogHandler(string message);
public void Process(LogHandler logHandler)
{
if (logHandler != null)
{
logHandler("Process() begin");
}

if (logHandler != null)
{
logHandler ("Process() end");
}
}
}
public class FileLogger
{
FileStream fileStream;
StreamWriter streamWriter;

public FileLogger(string filename)


{
fileStream = new FileStream(filename, FileMode.Create);
streamWriter = new StreamWriter(fileStream);
}
public void Logger(string s)
{
streamWriter.WriteLine(s);
}

public void Close()


{
streamWriter.Close();
fileStream.Close();
}
}
public class TestApplication
{
static void Logger(string s)
{
Console.WriteLine(s);
}
static void Main(string[] args)
{
FileLogger fl = new FileLogger("process.log");

Program myClass = new Program();

Program.LogHandler myLogger = null;


myLogger += new Program.LogHandler(Logger);
myLogger += new Program.LogHandler(fl.Logger);

myClass.Process(myLogger);
fl.Close();
}
}}

30 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program in c# to perform following tasks:

Copy data from two text files to a third file

Calculate length of the destination file

Handle exceptions while opening a file, reading or writing a file and wherever required.

Purpose of Program: Write a program to print size of all value types.

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

namespace Sample_Prg
{
class Program
{
static void Main(string[] args)
{
FileStream fin1 = null;
FileStream fin2 = null;
FileStream fout = null;
int i,len=0;
try
{
fin1 = new FileStream("Source1.txt", FileMode.OpenOrCreate);
fout = new FileStream("Destination.txt", FileMode.Create);
}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
try
{
do
{
i = fin1.ReadByte();

if (i != -1)
{
fout.WriteByte((byte)i);
len++;
}
} while (i != -1);

}
catch (IOException e)
{
Console.WriteLine("Error In Reading File");
Console.WriteLine(e.Message);
}
finally
{
if(fin1!=null) fin1.Close();
if (fout != null) fout.Close();
}

31 | P a g e
C# Programming Ketan Rajpal Practical File
try
{
fin2= new FileStream("Source2.txt",FileMode.OpenOrCreate);
fout = new FileStream("Destination.txt", FileMode.Append);

}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
try
{
do
{
i = fin2.ReadByte();

if (i != -1)
{
fout.WriteByte((byte)i);
len++;
}
} while (i != -1);
Console.WriteLine("File is copied");
Console.WriteLine("Length of the destination file is: " + len);

}
catch (IOException e)
{
Console.WriteLine("Error Reading File");
Console.WriteLine(e.Message);
}
finally
{
if (fin2 != null) fin1.Close();
if (fout != null) fout.Close();
}
}
}
}

Output:
File is copied
Length of the destination file is: 903
Press any key to continue . . .

32 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program that reads a 1-d array of integers. Using binary

search, find whether a number x is found in the array or not.


using System;

class ArrayBinarySearch
{
public static void Main()
{
int[] ints = {0, 10, 100, 1000, 1000000 };
Console.WriteLine ("Array indices and elements: ");
for (int i = 0; i < ints.Length; i++ )
{
Console.Write("[{0}]={1, -5}", i, ints[i]);
}
Console.WriteLine();
FindObject (ints, 25);
FindObject (ints, 1000);
FindObject (ints, 2000000);
}

public static void FindObject (Array array, Object o)


{
int index = Array.BinarySearch (array, 0, array.Length, o);
Console.WriteLine();
if (index > 0 )
{
Console.WriteLine ("Object: {0} found at [{1}]", o, index );
}
else if (~index == array.Length )
{
Console.WriteLine ("Object: {0} not found. "
+ "No array object has a greater value." , o);
Console.WriteLine ();
}
else
{
Console.WriteLine ("Object: {0} not found. "
+ "Next larger object found at [{1}].", o, ~index);
}
}
}

Output:
Array indices and elements:
[0]=0 [1]=10 [2]=100 [3]=1000 [4]=1000000

Object: 25 not found. Next larger object found at [2].


Object: 1000 found at [3]
Object: 2000000 not found. No array object has a greater value.

33 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program for sorting a 1-d array of strings, using:

1) Insertion sort 2) selection sort

Insertion Sort

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

namespace sortInsertion
{
class arraySort
{
private int[] a = new int[100];

private int x;

public void sortArray()


{
int i;
int j;
int index;

for (i = 1; i < x; i++)


{
index = a[i];
j = i;

while ((j > 0) && (a[j - 1] > index))


{
a[j] = a[j - 1];
j = j - 1;
}

a[j] = index;
}
}

public static void Main()


{
arraySort mySort = new arraySort();

Console.Write("Number of elements in the array (less than 100) : ");


string s = Console.ReadLine();
mySort.x = Int32.Parse(s);

Console.WriteLine("");
Console.WriteLine("-----------------------");
Console.WriteLine(" Enter array elements ");
Console.WriteLine("-----------------------");

for (int i = 0; i < mySort.x; i++)


{
Console.Write("<{0}> ", i + 1);
string s1 = Console.ReadLine();
mySort.a[i] = Int32.Parse(s1);
}

mySort.sortArray();

Console.WriteLine("");
Console.WriteLine("-----------------------");
Console.WriteLine(" Sorted array elements ");

34 | P a g e
C# Programming Ketan Rajpal Practical File
Console.WriteLine("-----------------------");

for (int j = 0; j < mySort.x; j++)


{
Console.WriteLine(mySort.a[j]);
}

Console.WriteLine("\n\nPress Return to exit.");


Console.Read();
}
}
}

Output:
Number of elements in the array (less than 100) : 10

-----------------------
Enter array elements
-----------------------
<1> 8
<2> 7
<3> 64
<4> 324
<5> 2
<6> 5
<7> 2
<8> 6
<9> 1
<10> 6

-----------------------
Sorted array elements
-----------------------
1
2
2
5
6
6
7
8
64
324
Press Return to exit.

Selection sort
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace sortSelection
{
class selectionSort
{
private int[] a = new int[100];

private int x;

public void sortArray()


{

35 | P a g e
C# Programming Ketan Rajpal Practical File
int i, j;
int min, temp;

for (i = 0; i < x - 1; i++)


{
min = i;

for (j = i + 1; j < x; j++)


{
if (a[j] < a[min])
{
min = j;
}
}

temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}

public static void Main()


{
selectionSort mySort = new selectionSort();
Console.Write("Number of elements in the array (less than 100) : ");
string s = Console.ReadLine();
mySort.x = Int32.Parse(s);

Console.WriteLine("");
Console.WriteLine("-----------------------");
Console.WriteLine(" Enter array elements ");
Console.WriteLine("-----------------------");

for (int i = 0; i < mySort.x; i++)


{
Console.Write("<{0}> ", i + 1);
string s1 = Console.ReadLine();
mySort.a[i] = Int32.Parse(s1);
}

mySort.sortArray();
Console.WriteLine("");
Console.WriteLine("-----------------------");
Console.WriteLine(" Sorted array elements ");
Console.WriteLine("-----------------------");

for (int j = 0; j < mySort.x; j++)


{
Console.WriteLine(mySort.a[j]);
}
Console.WriteLine("\n\nPress Return to exit.");
Console.Read();
}
}
}

Output:
Number of elements in the array (less than 100) : 10

-----------------------
Enter array elements
-----------------------
<1> 1
<2> 7
<3> 5
<4> 9

36 | P a g e
C# Programming Ketan Rajpal Practical File
<5> 3
<6> 2
<7> 4
<8> 5
<9> 6
<10> 4

-----------------------
Sorted array elements
-----------------------
1
2
3
4
4
5
5
6
7
9

Press Return to exit.

37 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program to implement the nested class concept.

class Demo
{
public static void Main()
{
System.Console.WriteLine("DemoClass");
}
}

class OuterClass
{
class NestedClass
{

}
public void CreateObjectOfNestedClass()
{
NestedClass obj = new NestedClass();
}
}

Output:
DemoClass

38 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Create a window form application such that when the mouse button is

clicked and moved in the form, a line is drawn corresponding to the mouse movement. Using

a mouse down event, identify whether the right or left mouse button is clicked and display

the appropriate message in the message box. For eg. right mouse button clicked!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
bool shouldpaint = false;
public Form1()
{
InitializeComponent();

}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button==MouseButtons.Left)
MessageBox.Show("Left Mouse Button clicked!");
else if(e.Button==MouseButtons.Right)
MessageBox.Show("Right Mouse Button clicked!");
shouldpaint = true;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
shouldpaint = false;
}

private void Form1_MouseMove(object sender, MouseEventArgs e)


{
if (shouldpaint)
{
Graphics g = this.CreateGraphics();
SolidBrush s = new SolidBrush(Color.Black);
g.FillEllipse(s, e.X, e.Y, 4, 4);
}
}
}
}

39 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Create a window form application to generate a tic-tac-toe program.

using System;
using System.Windows.Forms;
using System.Drawing;

namespace TicTacToeWin32
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button but1;
private System.Windows.Forms.Button but2;
private System.Windows.Forms.Button but3;
private System.Windows.Forms.Button but4;
private System.Windows.Forms.Button but5;
private System.Windows.Forms.Button but6;
private System.Windows.Forms.Button but7;
private System.Windows.Forms.Button but8;
private System.Windows.Forms.Button but9;
private System.Windows.Forms.Button butPlay;

private System.Windows.Forms.Button [] _buttonArray;


private bool _isX;
private bool _isGameOver;

private System.ComponentModel.Container components = null;

public Form1()
{
InitializeComponent();
}

protected override void Dispose( bool disposing )


{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code

private void InitializeComponent()


{
this.but1 = new System.Windows.Forms.Button();
this.but2 = new System.Windows.Forms.Button();
this.but3 = new System.Windows.Forms.Button();

40 | P a g e
C# Programming Ketan Rajpal Practical File
this.but4 = new System.Windows.Forms.Button();
this.but5 = new System.Windows.Forms.Button();
this.but6 = new System.Windows.Forms.Button();
this.but7 = new System.Windows.Forms.Button();
this.but8 = new System.Windows.Forms.Button();
this.but9 = new System.Windows.Forms.Button();
this.butPlay = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// but1
//
this.but1.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.but1.Location = new System.Drawing.Point(24, 16);
this.but1.Name = "but1";
this.but1.Size = new System.Drawing.Size(50, 50);
this.but1.TabIndex = 0;
//
// but2
//
this.but2.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.but2.Location = new System.Drawing.Point(72, 16);
this.but2.Name = "but2";
this.but2.Size = new System.Drawing.Size(50, 50);
this.but2.TabIndex = 1;
//
// but3
//
this.but3.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.but3.Location = new System.Drawing.Point(120, 16);
this.but3.Name = "but3";
this.but3.Size = new System.Drawing.Size(50, 50);
this.but3.TabIndex = 2;
//
// but4
//
this.but4.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.but4.Location = new System.Drawing.Point(24, 64);
this.but4.Name = "but4";
this.but4.Size = new System.Drawing.Size(50, 50);
this.but4.TabIndex = 3;
//
// but5
//
this.but5.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.but5.Location = new System.Drawing.Point(72, 64);
this.but5.Name = "but5";
this.but5.Size = new System.Drawing.Size(50, 50);
this.but5.TabIndex = 4;
//
// but6
//
this.but6.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.but6.Location = new System.Drawing.Point(120, 64);
this.but6.Name = "but6";
this.but6.Size = new System.Drawing.Size(50, 50);
this.but6.TabIndex = 5;
//
// but7
//
this.but7.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));

41 | P a g e
C# Programming Ketan Rajpal Practical File
this.but7.Location = new System.Drawing.Point(24, 112);
this.but7.Name = "but7";
this.but7.Size = new System.Drawing.Size(50, 50);
this.but7.TabIndex = 6;
//
// but8
//
this.but8.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.but8.Location = new System.Drawing.Point(72, 112);
this.but8.Name = "but8";
this.but8.Size = new System.Drawing.Size(50, 50);
this.but8.TabIndex = 7;
//
// but9
//
this.but9.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.but9.Location = new System.Drawing.Point(120, 112);
this.but9.Name = "but9";
this.but9.Size = new System.Drawing.Size(50, 50);
this.but9.TabIndex = 8;
//
// butPlay
//
this.butPlay.Location = new System.Drawing.Point(56, 176);
this.butPlay.Name = "butPlay";
this.butPlay.TabIndex = 9;
this.butPlay.Text = "Play";
this.butPlay.Click += new System.EventHandler(this.butPlay_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(192, 213);
this.Controls.AddRange(new System.Windows.Forms.Control[] {

this.butPlay,

this.but9,

this.but8,

this.but7,

this.but6,

this.but5,

this.but4,

this.but3,

this.but2,

this.but1});
this.Name = "Form1";
this.Text = "Tic Tac Toe for Windows Forms";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);

}
#endregion

[STAThread]
static void Main()
{

42 | P a g e
C# Programming Ketan Rajpal Practical File
Application.Run(new Form1());
}

private void Form1_Load(object sender, System.EventArgs e)


{
_buttonArray = new Button[9] {but1, but2, but3, but4, but5, but6,
but7, but8, but9};

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


this._buttonArray[i].Click += new
System.EventHandler(this.ClickHandler);

InitTicTacToe();
}

private void butPlay_Click(object sender, System.EventArgs e)


{
InitTicTacToe();
}

private void InitTicTacToe()


{
for(int i=0;i<9;i++)
{
_buttonArray[i].Text = "";
_buttonArray[i].ForeColor = Color.Black;
_buttonArray[i].BackColor = Color.LightGray;
_buttonArray[i].Font = new System.Drawing.Font("Microsoft Sans
Serif", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point,
((System.Byte)(0)));
}
this._isX = true;
this._isGameOver = false;
}

private void ClickHandler(object sender, System.EventArgs e)


{
Button tempButton = (Button)sender;

if( this._isGameOver )
{
MessageBox.Show("Game Over...Select Play for a new
game!","ERROR",MessageBoxButtons.OK);
return;
}

if( tempButton.Text != "" )


{
MessageBox.Show("Button already has
value!","ERROR",MessageBoxButtons.OK);
return;
}

if( _isX )
tempButton.Text = "X";
else
tempButton.Text = "O";

_isX = !_isX;

this._isGameOver = TicTacToeUtils.CheckAndProcessWinner(_buttonArray
);
}
}
public class TicTacToeUtils
{
static private int [,] Winners = new int[,]

43 | P a g e
C# Programming Ketan Rajpal Practical File
{
{0,1,2},
{3,4,5},
{6,7,8},
{0,3,6},
{1,4,7},
{2,5,8},
{0,4,8},
{2,4,6}
};
static public bool CheckAndProcessWinner( Button [] myControls )
{
bool gameOver = false;
for(int i = 0; i < 8; i++)
{
int a = Winners[i,0],b=Winners[i,1],c=Winners[i,2];
Button b1=myControls[a], b2=myControls[b], b3=myControls[c];
if(b1.Text == "" || b2.Text == "" || b3.Text == "" )
continue;

if(b1.Text == b2.Text && b2.Text == b3.Text )


{

b1.BackColor = b2.BackColor = b3.BackColor =


Color.LightCoral;
b1.Font = b2.Font = b3.Font = new
System.Drawing.Font("Microsoft Sans Serif", 32F, System.Drawing.FontStyle.Italic &
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
gameOver = true;
break;
}
}
return gameOver;
}
}
}

44 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Create a window form application to design and implement a

calculator.
using System;
using System.Windows.Forms;
using System.Drawing;

public class win:Form {

Button[] b = new Button[10];


Button bDot,bPlus,bSub,bMul,bDiv,bEqu,bClr;
Panel panCalc;
TextBox txtCalc;

Double dblAcc;
Double dblSec;
bool blnClear,blnFrstOpen;
String strOper;

public win() {
try {
this.Text="Calculator";
panCalc=new Panel();
txtCalc = new TextBox();

txtCalc.Location = new Point(10,10);


txtCalc.Size=new Size(150,10);
txtCalc.ReadOnly=true;
txtCalc.RightToLeft=RightToLeft.Yes;
panCalc.Size=new Size(200,200);
panCalc.BackColor=Color.Aqua;
panCalc.Controls.Add(txtCalc);
addButtons(panCalc);
this.Size=new Size(200,225);
this.Controls.Add(panCalc);

dblAcc=0;
dblSec=0;
blnFrstOpen=true;
blnClear=false;
strOper=new String('=',1);
}
catch (Exception e) {
Console.WriteLine("error ...... " + e.StackTrace);
}
}

private void addButtons(Panel p) {


for (int i=0;i<=9;i++) {
b[i]=new Button();
b[i].Text=Convert.ToString(i);
b[i].Size=new Size(25,25);
b[i].BackColor=Color.White;
b[i].Click+=new EventHandler(btn_clk);
p.Controls.Add(b[i]);
}
b[0].Location=new Point(10,160);
b[1].Location=new Point(10,120);

45 | P a g e
C# Programming Ketan Rajpal Practical File
b[4].Location=new Point(10,80);
b[7].Location=new Point(10,40);

b[2].Location=new Point(50,120);
b[5].Location=new Point(50,80);
b[8].Location=new Point(50,40);

b[3].Location=new Point(90,120);
b[6].Location=new Point(90,80);
b[9].Location=new Point(90,40);

bDot=new Button();
bDot.Size=new Size(25,25);
bDot.Location=new Point(50,160);
bDot.BackColor=Color.White;
bDot.Text=".";
bDot.Click+=new EventHandler(btn_clk);

bPlus=new Button();
bPlus.Size=new Size(25,25);
bPlus.Location=new Point(130,160);
bPlus.BackColor=Color.White;
bPlus.Text="+";
bPlus.Click+=new EventHandler(btn_Oper);

bSub=new Button();
bSub.Size=new Size(25,25);
bSub.Location=new Point(130,120);
bSub.BackColor=Color.White;
bSub.Text="-";
bSub.Click+=new EventHandler(btn_Oper);

bMul=new Button();
bMul.Size=new Size(25,25);
bMul.Location=new Point(130,80);
bMul.BackColor=Color.White;
bMul.Text="*";
bMul.Click+=new EventHandler(btn_Oper);

bDiv=new Button();
bDiv.Size=new Size(25,25);
bDiv.Location=new Point(130,40);
bDiv.BackColor=Color.White;
bDiv.Text="/";
bDiv.Click+=new EventHandler(btn_Oper);

bEqu=new Button();
bEqu.Size=new Size(25,25);
bEqu.Location=new Point(90,160);
bEqu.BackColor=Color.White;
bEqu.Text="=";
bEqu.Click+=new EventHandler(btn_equ);

bClr=new Button();
bClr.Size=new Size(20,45);
bClr.Location=new Point(170,40);
bClr.BackColor=Color.Orange;
bClr.Text="AC";
bClr.Click+=new EventHandler(btn_clr);

46 | P a g e
C# Programming Ketan Rajpal Practical File

p.Controls.Add(bDot);
p.Controls.Add(bPlus);
p.Controls.Add(bSub);
p.Controls.Add(bMul);
p.Controls.Add(bDiv);
p.Controls.Add(bEqu);
p.Controls.Add(bClr);
}

private void btn_clk(object obj,EventArgs ea) {


if(blnClear)
txtCalc.Text="";

Button b3=(Button)obj;

txtCalc.Text+=b3.Text;

if (txtCalc.Text==".")
txtCalc.Text="0.";
dblSec=Convert.ToDouble(txtCalc.Text);

blnClear=false;
}

private static void Main() {


Application.Run(new win());
}

private void btn_Oper(object obj,EventArgs ea) {


Button tmp=(Button)obj;
strOper=tmp.Text;
if (blnFrstOpen)
dblAcc=dblSec;
else
calc();

blnFrstOpen=false;
blnClear=true;
}

private void btn_clr(object obj,EventArgs ea) {


clear();
}

private void btn_equ(object obj,EventArgs ea) {


calc();

private void calc() {

switch(strOper) {

case "+":
dblAcc+=dblSec;
break;
case "-":
dblAcc-=dblSec;

47 | P a g e
C# Programming Ketan Rajpal Practical File
break;
case "*":
dblAcc*=dblSec;
break;
case "/":
dblAcc/=dblSec;
break;
}

strOper="=";
blnFrstOpen=true;
txtCalc.Text=Convert.ToString(dblAcc);
dblSec=dblAcc;
}

private void clear() {


dblAcc=0;
dblSec=0;
blnFrstOpen=true;
txtCalc.Text="";
txtCalc.Focus();

}
}

48 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Create a window form application to design the following form[make

use of delegates and events]:

Write code to add different colors name to the list box the item should appear in

the list box in the alphabetically sorted order.

Add button, adds the text into the list box that was typed into the textbox it then

clears the textbox. The current no. Of list box items should be displayed on the

label. The focus is again set back to the textbox for adding new item.

Remove button remove the selected item from the listbox and label that displays

the item is decremented if none of the item is selected then remove button is

disabled..

Clear button clears all the items in the listbox. Then disables the remove command

button and label that display the list item becomes zero.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox1.Text);
textBox1.Clear();
button2.Enabled = true;
label2.Text=(listBox1.Items.Count).ToString();
textBox1.TabIndex = 0;
textBox1.Focus();
}
private void button2_Click(object sender, EventArgs e)
{
listBox1.Items.Remove(listBox1.SelectedItem);
label2.Text = (listBox1.Items.Count).ToString();
}
private void button3_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
button2.Enabled = false;
label2.Text = (listBox1.Items.Count).ToString();

49 | P a g e
C# Programming Ketan Rajpal Practical File
}
private void button4_Click(object sender, EventArgs e)
{
listBox1.Sorted=true;

}
}
}

Output:

50 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program in c++ to define an interface ishape that can describe

any simple shape such as square, circle or rectangle. The size of all these shapes can be

reduced to a single dimension. Create classes for each of these three shapes, that implement

ishape interface. Create an abstract function in the ishape interface that returns area of each

shape. Now, create an array of heterogeneous shapes and display area of shape stored in the

array.

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

namespace Sample_Prg
{
public interface IShape
{
double Area();
}
class Square : IShape
{
double side;
public Square(double s)
{
side = s;
}
public double Area()
{
Console.WriteLine("Area of Square");
return (side * side);
}

}
class Rectangle : IShape
{
double len;
double br;
public Rectangle(double l, double b)
{
len = l;
br = b;
}
public double Area()
{
Console.WriteLine("Area of Rectangle");
return (len * br);
}
}
class Circle : IShape
{
double rad;
public Circle(double r)
{
rad = r;
}

51 | P a g e
C# Programming Ketan Rajpal Practical File
public double Area()
{
Console.WriteLine("Area of Circle");
return ((Math.PI) * rad * rad);
}

class Program
{
static void Main(string[] args)
{
Circle c = new Circle(10);
Rectangle r = new Rectangle(10, 20);
Square s = new Square(5);
IShape[] obj = { r, c, s };
for (int i = 0; i < 3; i++)
Console.WriteLine(obj[i].Area());
}
}
}

Output:
Area of Rectangle
200
Area of Circle
314.159265358979
Area of Square
25
Press any key to continue . . .

52 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Create a student class, with attribute name and rollno. Derive a class

exams from it with attribute int [] marks, which is an array of marks in 5 subjects. Derive a

class result from it, which calculates total marks and prints it. There are read and write

methods in each of the classes. Use concept of virtual keyword. Also, use new keyword to

provide a new implementation of the read method in the result class.

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

namespace Sample_Prg
{
class Student
{
protected string name;
protected long rollno;
public virtual void Read()
{
Console.WriteLine("Enter the name of the student: ");
name = Console.ReadLine();
Console.WriteLine("Enter the Roll no. of the student: ");
rollno = Int64.Parse(Console.ReadLine());
}
public virtual void Write()
{
Console.WriteLine("Name:\t" + name);
Console.WriteLine("Roll no.:\t" + rollno);
}
}
class Exam : Student
{
protected int[] marks=new int[5];
public override void Read()
{
base.Read();
Console.WriteLine("Enter the marks of 5 subjects");
for (int i = 0; i < 5; i++)
marks[i] = Int32.Parse(Console.ReadLine());
}
public override void Write()
{
base.Write();
Console.WriteLine("Marks in 5 subjects: ");
for (int i = 0; i < 5; i++)
Console.WriteLine("Subject{0}:\t{1}", i, marks[i]);
}

}
class Result : Exam
{
protected int tmarks=0;
string course;

53 | P a g e
C# Programming Ketan Rajpal Practical File
public void Tmarks()
{
for (int i = 0; i < 5; i++)
tmarks+=marks[i];

Console.WriteLine("Total marks:\t",tmarks);
}
new public void Read()
{
base.Read();
Console.WriteLine("Enter course of the student: ");
course = Console.ReadLine();

}
}
class Program
{
static void Main(string[] args)
{
Result r = new Result();
r.Read();
r.Write();
r.Tmarks();
}
}
}

Output:
Enter the name of the student:
Ajay Kumar Verma
Enter the Roll no. of the student:
0116204410
Enter the marks of 5 subjects
60
70
80
90
95
Enter course of the student:
MCA
Name: Ajay Kumar Verma
Roll no.: 116204410
Marks in 5 subjects:
Subject0: 60
Subject1: 70
Subject2: 80
Subject3: 90
Subject4: 95
Course: MCA
Total marks: 395
Press any key to continue . . .

54 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Create an application that defines a user-defined exception class

negativenumexception. When user enters a positive numeric value, its square root is

calculated. If the negative value is entered, then negativenumexception exception is thrown.


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

namespace Sample_Prg
{
class NegetiveNumException: Exception
{
public static void Sqroot(int n)
{
try
{
if (n < 0)
throw new NegetiveNumException();

Console.WriteLine("Square root of {0}: {1}",n,Math.Sqrt(n));


}
catch (NegetiveNumException)
{
Console.WriteLine("Negative Number Exception");
}
}
}
class Program
{
static void Main(string[] args)
{
int num;
Console.WriteLine("Enter the number: ");
num=Int32.Parse(Console.ReadLine());
NegetiveNumException.Sqroot(num);

}
}
}

Output:
Enter the number:
49
Square root of 49: 7
Press any key to continue . . .

Enter the number:


42
Square root of 42: 6.48074069840786
Press any key to continue . . .

Enter the number:


-9
Negative Number Exception

55 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program to raise an exception whenever 2 numbers are

divided, in order to handle divide by zero exception.

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

namespace divide
{
class Program
{
static void Main(string[] args)
{
int firstNumber, secondNumber, result;
Console.WriteLine("WELCOME TO DIVIDE PROGRAM");
Console.WriteLine("Enter the first number: ");
firstNumber = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number: ");
secondNumber = Convert.ToInt32(Console.ReadLine());
try
{
result = firstNumber / secondNumber;
Console.WriteLine("The result is: " + (result).ToString());
}
catch (DivideByZeroException e)
{
Console.WriteLine("Divide by ZERO (0) Exception.");
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}

Output:
WELCOME TO DIVIDE PROGRAM
Enter the first number:
1
Enter the second number:
0
Divide by ZERO (0) Exception.
Attempted to divide by zero.

56 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program in c# to implement a user-defined generic mehod.


using System;
class ArrayUtils
{
public static bool CopyInsert<T>(T e, uint idx,T[] src, T[] target)
{
if(target.Length < src.Length+1)
return false;
for(int i=0, j=0; i < src.Length; i++, j++)
{
if(i == idx)
{
target[j] = e;
j++;
}
target[j] = src[i];
}
return true;
}
}

class GenMethDemo {
static void Main() {
int[] nums = { 1, 2, 3 };
int[] nums2 = new int[4];
Console.Write("Contents of nums: ");
foreach(int x in nums)
Console.Write(x + " ");
Console.WriteLine();
ArrayUtils.CopyInsert(99, 2, nums, nums2);
Console.Write("Contents of nums2: ");
foreach(int x in nums2)
Console.Write(x + " ");
Console.WriteLine();
string[] strs = { "Generics", "are", "powerful."};
string[] strs2 = new string[4];
Console.Write("Contents of strs: ");
foreach(string s in strs)
Console.Write(s + " ");
Console.WriteLine();
ArrayUtils.CopyInsert("in C#", 1, strs, strs2);
Console.Write("Contents of strs2: ");
foreach(string s in strs2)
Console.Write(s + " ");
Console.WriteLine();
}
}

Output:
Contents of nums: 1 2 3
Contents of nums2: 1 2 99 3
Contents of strs: Generics are powerful.
Contents of strs2: Generics in C# are powerful.

57 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program using generic collection list<t> to do the following:

Create an employee class

Store 10 employee objects in list<t>

Using ienumeratot<t>, iterate through the list collection of employee objects.

Display the first and last object of the list.

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

namespace Sample_Prg
{
class Employee
{
int Empid;
string Name;
long phno;
public Employee(int ed, string n, long ph)
{
Empid = ed;
Name = n;
phno = ph;
}

public void Display()


{
Console.WriteLine("Employee id: " + Empid);
Console.WriteLine("Name: " + Name);
Console.WriteLine("Phone Number: " + phno);
}
}

class Program
{
static void Main(string[] args)
{
int i = 0;
int id;
string n;
long ph;
List<Employee> list = new List<Employee>();
Console.WriteLine("---Enter the Employee Records----");
do
{
Console.WriteLine("\nEmployee:\t " + (i + 1));
Console.Write("\nEnter employee id: ");
id = Int32.Parse(Console.ReadLine());
Console.Write("\nEnter Name: ");
n = Console.ReadLine();
Console.Write("\nEnter Phone Number: ");
ph = Int64.Parse(Console.ReadLine());
list.Add(new Employee(id, n, ph));
i++;
} while (i < 10);

58 | P a g e
C# Programming Ketan Rajpal Practical File
IEnumerable < Employee >l1= list;
Console.WriteLine("\n\n------ Employee Database-----");
foreach (Employee q in l1)
{
q.Display();
}
Console.WriteLine("\n----First Object of the List is:---- ");
var q1 = list.First();
q1.Display();

Console.WriteLine("\n----Last Object of the List is:---- ");


var q2 = l1.Last();
q2.Display();
}
}
}

Output:
---Enter the Employee Records----

Employee: 1

Enter employee id: 102

Enter Name: Ajay Devgan

Enter Phone Number: 9989898998

Employee: 2

Enter employee id: 101

Enter Name: Amir Khan

Enter Phone Number: 9898989898

Employee: 3

Enter employee id: 130

Enter Name: Amitab Bacchan

Enter Phone Number: 9894556133

Employee: 4

Enter employee id: 23

Enter Name: Ranbir Kapoor

Enter Phone Number: 9626262626

Employee: 5

Enter employee id: 109

Enter Name: Nasaruddin Sha

59 | P a g e
C# Programming Ketan Rajpal Practical File

Enter Phone Number: 9011011011

Employee: 6

Enter employee id: 45

Enter Name: Lovely Singh

Enter Phone Number: 9878565656

Employee: 7

Enter employee id: 52

Enter Name: Salman Khan

Enter Phone Number: 9825635669

Employee: 8

Enter employee id: 50

Enter Name: Hrithik Roshan

Enter Phone Number: 9589556989

Employee: 9

Enter employee id: 56

Enter Name: Sharuk Khan

Enter Phone Number: 9698996562

Employee: 10

Enter employee id: 56

Enter Name: Nana Patekar

Enter Phone Number: 9556565656

------ Employee Database-----


Employee id: 102
Name: Ajay Devgan
Phone Number: 9989898998

Employee id: 101


Name: Amir Khan
Phone Number: 9898989898

Employee id: 56
Name: Nana Patekar
Phone Number: 5656565656

60 | P a g e
C# Programming Ketan Rajpal Practical File
----First Object of the List is:----
Employee id: 102
Name: Ajay Devgan
Phone Number: 9989898998

----Last Object of the List is:----


Employee id: 56
Name: Nana Patekar
Phone Number: 5656565656
Press any key to continue . . .

61 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program using dicionary<k,t> to do the following:

Implement a telephone directory of names and phone numbers

Search the telephone number, given name as input, from the above directory.

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

namespace Sample_Prg
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, long> Dict = new Dictionary<string, long>();
Dict.Add("Ajay", 9990116347);
Dict.Add("Himanshu", 9899889998);
Dict.Add("Jitin", 9990116347);
Dict.Add("Pinki", 9999889998);
Dict.Add("Ravish", 9898977777);
Dict.Add("Ekta", 9991116247);
Dict.Add("Manisha", 9211889998);
Dict.Add("Rohit",9098989898);
Dict.Add("Ramesh", 9999226347);
Dict.Add("Mansi", 9099899998);

ICollection<string> c = Dict.Keys;
string ns;
long ps=0;
bool flag= false;
Console.WriteLine("------- Student Contact Details--------\n");
Console.WriteLine("Enter correct Name to find his/her Phone no.");
ns = Console.ReadLine();
foreach (var n in c)
{
if (n == ns)
{
ps = Dict[n];
flag = true;
}

}
if (flag)
Console.WriteLine("Name: {0}, Phone no.: {1}", ns, ps);
else
Console.WriteLine("Record Not Found");
}
}
}
Output:
------- Student Contact Details--------

Enter correct Name to find his/her Phone no.


Ajay
Name: Ajay, Phone no.: 9990116347

62 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a console application to check whether a given number is even or

odd in a list<t> of integers. Return the list of even numbers and odd numbers present in the

given list. Use lambda expression to create even function and anonymous delegate to create

function for checking odd numbers.

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

namespace Sample_Prg
{ delegate bool CheckOdd(int i);
delegate bool CheckEven(int j);
class Program
{
static void Main(string[] args)
{
CheckEven isEven = count =>count % 2==0;
CheckOdd isOdd = delegate(int n)
{
if (n % 2 == 0)
return false;
else
return true;
};
int[] arr = {2,3,4,16,57,8,99,45,22,5};
List<int>l= new List<int>();
l.AddRange(arr);
foreach (var i in l)
{
if (isEven(i))
Console.WriteLine(i + " is even.");
}
foreach (var i in l)
{
if (isOdd(i))
Console.WriteLine(i + " is Odd.");
}
}
}
}

Output:
2 is even.
4 is even.
16 is even.
8 is even.
22 is even.

3 is Odd.
57 is Odd.
99 is Odd.
45 is Odd.
5 is Odd.

63 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a program in c# to implement a generic delegate type.


using System;
delegate T SomeOp<T>(T v);
class GenDelegateDemo
{
static int Sum(int v)
{
int result = 0;
for(int i=v; i>0; i--)
result += i;
return result;
}

static string Reflect(string str)


{
string result = "";
foreach(char ch in str)
result = ch + result;
return result;
}

static void Main()


{
SomeOp<int> intDel = Sum;
Console.WriteLine(intDel(3));
SomeOp<string> strDel = Reflect;
Console.WriteLine(strDel("Hello"));
}
}

Output:
6
olleH

64 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Implement a simple paint application using gdi+.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Paint__app
{
public partial class Form1 : Form
{
bool paint = false;
SolidBrush color;
public Form1()
{
InitializeComponent();
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (paint)
{
color = new SolidBrush(Color.Black);
Graphics g = panel1.CreateGraphics();
g.FillEllipse(color, e.X, e.Y, 5, 5);
g.Dispose();
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
paint = true;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
paint = false;
}
private void Clear_Click(object sender, EventArgs e)
{
Graphics g1 = panel1.CreateGraphics();
g1.Clear(panel1.BackColor);
}
private void Close_Bt_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

65 | P a g e
C# Prrogramming Ketaan Rajpal Praactical File

Purp
pose of Pro
ogram: Imp
plement a complete w
wpf application.

XAM
ML Code

<Win
ndow x:Clas
ss="myFirs
stWPFApplic
cation.Mai
inWindow"
xmlns=
="http://s
schemas.mic
crosoft.co
om/winfx/20
006/xaml/p
presentatio
on"
xmlns:
:x="http:/
//schemas.m
microsoft.com/winfx/
/2006/xaml
l"
Title=
="My First
t W.P.F App
plication"
" Height="3
350" Width
h="750">
<Grid>
<ListB
Box Height
t="161" Hor
rizontalAl
lignment="L
Left" Marg
gin="175,12
2,0,0"
Name
e="dataList
t" Vertica
alAlignment
t="Top" Wi
idth="133" />
<Label
l Content=
="Data you entered(L
List Box):"
" Height="
"28"
Hori
izontalAlig
gnment="Le
eft" Margin
n="12,12,0
0,0" Name="
"label1" V
VerticalAli
ignment="T
Top"
Widt
th="157" />
>
<Label
l Content=
="Data you entered(C
Combo Box):
:" Height=
="28"
Hori
izontalAlig
gnment="Le
eft" Margin ="label2" VerticalAl
n="356,12,0,0" Name= lignment="
"Top" />
<Combo
oBox Heigh
ht="23" Hor
rizontalAl
lignment="R
Right" Mar
rgin="0,17,
,24,0"
Name
e="dataComb
bo" Vertic
calAlignmen
nt="Top" W
Width="169"
" />
<Butto
on Content
t="Add Data
a" Height=
="23" Horiz
zontalAlig
gnment="Lef
ft"
gin="391,21
Marg 18,0,0" Na
ame="addBut
tton" Vert
ticalAlignm
ment="Top"
" Width="75
5"
Clic
ck="addButt
ton_Click"
" />
<TextB
Box Height
t="23" Hori
izontalAli
ignment="Le
eft" Margi
in="175,218
8,0,0"
Name
e="dataText
t" Vertica
alAlignment
t="Top" Wi
idth="188" />
<Label
l Content=
="Enter dat
ta you wan
nt to add:"
" Height="
"28"
Hori
izontalAlig
gnment="Le
eft" Margin ="label3" VerticalAl
n="13,215,0,0" Name= lignment="
"Top" />
<Butto
on Content
t="Delete Selected
S D
Data" Heigh
ht="23" Ho
orizontalAl
lignment="
"Left"
gin="175,25
Marg 55,0,0" Na
ame="delete
eButtton" VerticalAl
lignment="
"Top" Width
h="129"
Clic
ck="deleteB
Buttton_Cl
lick" />
<Butto
on Content
t="Clear" Height="23
H 3" Horizont
talAlignme
ent="Right"
"
Marg
gin="0,255,
,262,0" Na
ame="clearB
Button" Ve
erticalAlig
gnment="To
op" Width="
"75"
Clic
ck="clearBu
utton_Clic
ck" />
<Butto
on Content
t="Sort Dat
ta" Height
t="23" Hori
izontalAli
ignment="Le
eft"
Marg
gin="310,25
55,0,0" Na
ame="sortBu
utton" Ver
rticalAlign
nment="Top
p" Width="7
75"
Clic
ck="sortBut
tton_Click
k" />
</Grid>
</Wi
indow>

C# Co
ode

usin
ng System;
usin
ng System.C
Collectionns.Generic;
;
usin
ng System.L
Linq;
usin
ng System.T
Text;
usin
ng System.W
Windows;
i S t W
Wi d C t l
C# Programming Ketan Rajpal Practical File
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace myFirstWPFApplication
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void addButton_Click(object sender, RoutedEventArgs e)


{
dataCombo.Items.Add(dataText.Text);
dataList.Items.Add(dataText.Text);
}

private void clearButton_Click(object sender, RoutedEventArgs e)


{
dataCombo.Items.Clear();
dataList.Items.Clear();
}

private void sortButton_Click(object sender, RoutedEventArgs e)


{
dataList.Items.SortDescriptions.Add(new
System.ComponentModel.SortDescription("",
System.ComponentModel.ListSortDirection.Ascending));
dataCombo.Items.SortDescriptions.Add(new
System.ComponentModel.SortDescription("",
System.ComponentModel.ListSortDirection.Ascending));
}

private void deleteButtton_Click(object sender, RoutedEventArgs e)


{
if (dataList.SelectedIndex > -1)
{
dataList.Items.RemoveAt(dataList.SelectedIndex);
dataList.Items.Refresh();
}

if (dataCombo.SelectedIndex > -1)


{
dataCombo.Items.RemoveAt(dataCombo.SelectedIndex);
dataCombo.Items.Refresh();
}
}
}
}

67 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a console application that creates a customer class and stores

student objects in a list<t>. The customer class has three properties: firstname, lastname,

and emailaddress. It overrides the object.tostring( ) method to provide a string

representation of its instances. Write a linq query to retrieve all customer objects whose first

name is donna from the customer list, and then update firstname of the fourth customer

in the list as donna.

using System;
using System.Collections.Generic;
using System.Linq;
namespace Programming_CSharp
{
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public override string ToString( )
{
return string.Format("{0} {1}\nEmail: {2}",
FirstName, LastName, EmailAddress);
}
}
public class Tester
{
static void Main( )
{
List<Customer> customers = CreateCustomerList( );
IEnumerable<Customer> result = from customer in customers
where customer.FirstName == "Donna"
select customer;
Console.WriteLine("FirstName == \"Donna\"");
foreach (Customer customer in result)
Console.WriteLine(customer.ToString( ));
customers[3].FirstName = "Donna";
Console.WriteLine("FirstName == \"Donna\" (take two)");
foreach (Customer customer in result)
Console.WriteLine(customer.ToString( ));
}
private static List<Customer> CreateCustomerList()
{
List<Customer> customers = new List<Customer>
{
new Customer { FirstName = "Orlando",
LastName = "Gee",
EmailAddress = "orlando0@adventure-works.com"},
new Customer { FirstName = "Keith",
LastName = "Harris",
EmailAddress = "keith0@adventure-works.com" },
new Customer { FirstName = "Donna",
LastName = "Carreras",
EmailAddress = "donna0@adventure-works.com" },
new Customer { FirstName = "Janet",
LastName = "Gates",
EmailAddress = "janet1@adventure-works.com" },
new Customer { FirstName = "Lucy",
LastName = "Harrington",
EmailAddress = "lucy0@adventure-works.com" }
};
return customers;
}
}}

68 | P a g e
C# Programming Ketan Rajpal Practical File

Output:

FirstName == "Donna"
Donna Carreras
Email: donna0@adventure-works.com
FirstName == "Donna" (take two)
Donna Carreras
Email: donna0@adventure-works.com
Donna Gates
Email: janet1@adventure-works.com

69 | P a g e
C# Programming Ketan Rajpal Practical File

Purpose of Program: Write a console program in c# to demonstrate the use of anonymous

types in a linq join query.


using System;
using System.Linq;
class Item
{
public string Name { get; set; }
public int ItemNumber { get; set; }
public Item(string n, int inum)
{
Name = n;
ItemNumber = inum;
}
}

class InStockStatus
{
public int ItemNumber { get; set; }
public bool InStock { get; set; }
public InStockStatus(int n, bool b)
{
ItemNumber = n;
InStock = b;
}
}

class AnonTypeDemo
{
static void Main()
{
Item[] items =
{
new Item("Pliers", 1424),
new Item("Hammer", 7892),
new Item("Wrench", 8534),
new Item("Saw", 6411)
};

InStockStatus[] statusList =
{
new InStockStatus(1424, true),
new InStockStatus(7892, false),
new InStockStatus(8534, true),
new InStockStatus(6411, true)
};

var inStockList = from item in items


join entry in statusList
on item.ItemNumber equals entry.ItemNumber
select new { Name = item.Name,
InStock = entry.InStock };
Console.WriteLine("Item\tAvailable\n");
foreach(var t in inStockList)
Console.WriteLine("{0}\t{1}", t.Name, t.InStock);
}
}

Output:
Item Available
Pliers True
Hammer False
Wrench True
Saw True

70 | P a g e