Sei sulla pagina 1di 34

PES University

DEPARTMENT OF BCA

.NET LABORATORY MANUAL


SUBCODE: UC14BC254
SEMESTER: IV SEMESTER

PREPARED BY:
P.SREENIVAS, ASST.PROFESSOR
DEPARTMENT OF MCA, PESIT

.Net Laboratory

Subject Code: UC14BC254


Total Hours: 26 (1C)

Hrs / week: 02
Exercises

Time

Sl.
No.

1.

Getting Started with Technology and writing basic programs like Hello
world in C#.

2 Hours

2.

Programs in C# to demonstrate the usage of Classes & Objects.

2 Hours

3.

Write a Program in C# to demonstrate the usage of Decision making,


Looping & branching.

2 Hours

4.

Write Programs to demonstrate the concepts of Arrays, Multidimensional


Arrays and Jagged Arrays

2 Hours

5.

Write Programs in C# to demonstrate boxing and Unboxing

2 Hours

6.

Write Programs in C# to demonstrate Single Level Inheritance, Multilevel


Inheritance

2 Hours

7.

Write a program to Demonstrate interfaces in C#.

2 Hours

8.

Write programs in C# to demonstrate Operator overloading, Virtual and


Override Keywords, Abstract class and Abstract Methods

2 Hours

9.

Write a program to illustrate the use of different properties in C#


(ENCAPSULATION).
Write a Program in C# to demonstrate the usage of Indexers

2 Hours

10.

Write a program in C# to demonstrate CONSOLE I/O


OPERATIONS(Numerical formatting, Console IO of both number &
strings)

2 Hours

11.

Using Try, Catch and Finally blocks write a program in C# to demonstrate


Exception Handling

2 Hours

12.

Write a program in C# to demonstrate of Simple delegates without


events.

2 Hours

Write a Program in C# to demonstrate Delegates with Events


13.

Final Test

2 Hours

Getting started with C#


1. Write a Program in C# to display a simple message Hello World
using System;
class demonstrate{
public static void Main()
{
Console.WriteLine(Hello world);
Console.ReadLine();
}
}

2. Write a Program in C# to demonstrate the usage of Classes & Objects.


using System;
namespace ConsoleApplication1
{

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

Car car;
car = new Car("Red");
Console.WriteLine(car.Describe());
car = new Car("Green");
Console.WriteLine(car.Describe());
Console.ReadLine();

class Car
{
private string color;
public Car(string color)
{

this.color = color;

public string Describe()


{

return "This car is " + Color;

public string Color


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

3. Write a Program in C# to demonstrate the usage of Decision making, looping &


branching.
Decision Making
using System;
public class Example
{
static void Main()
{ int a = 5, b = 2;
int result = a / b;
if (result == 2)
{ Console.WriteLine("Result is 2"); }
if (result == 3) { Console.WriteLine("Result is 3"); }
Console.ReadLine();
}}
Switch Statement
using System;
class Program
{
static void Main()
{
int x = 3;
switch (x)
{
case 1:
Console.WriteLine("x is equal to 1");
break;
case 2:
Console.WriteLine("x is equal to 2");
break;
case 3:
goto default;
default:
Console.WriteLine("x is equal to neither 1 nor 2");
break;
}}}
}
//for loop

using System;
namespace Examples1
{
class Program
{
static void Main(string[] args)
{
int num, i,result;
Console.Write("Enter a number\t");
num = Convert.ToInt32(Console.ReadLine());
for (i = 1; i <= 10; i++)
{
result = num * i;
Console.WriteLine("{0} x {1} = {2}", num, i,result);
}
Console.ReadLine();
}
}
}
//Do-While Loop
using System;
class Program
{
static void Main()
{
int[] ids = new int[] { 6, 7, 8, 10 };
int sum = 0;
int i = 0;
do
{
sum += ids[i];

i++;
} while (i < 4);
System.Console.WriteLine(sum);

Console.ReadLine();
}
}
//while loop
using System;
class Program
{
static void Main()
{
int i = 0;
while (i < 10)
{
Console.Write("While statement ");
Console.WriteLine(i);
i++;
}Console.ReadLine();
}
}

4. Write a Program to demonstrate the concept of Arrays.


using System;
class Program{
static void Main()

string[,] array = new string[,]


{
{"a", "d"},

{"b", "f"},
};
Console.WriteLine(array[0, 0]);
Console.WriteLine(array[0, 1]);
Console.WriteLine(array[1, 0]);
Console.WriteLine(array[1, 1]);
}
}

..............................
using System;
public class InitArray
{

static void Main()


{

int[] array = new int[5];


array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
for (int i = 0; i < array.Length; i++)
{
}

Console.WriteLine(array[i]);
}}

//JAGGED ARRAYS..........
Write a Program in C# to find the sum of all the elements present in a jagged array
of 3 inner arrays.
using System;
class MainClass
{
public static void Main (string[] args)
{

int sum = 0;
int[][] x = new int[3][];
x[0]=new int[3];
x[0]=new int[4];
x[0]=new int[5];
for (int j=0; j<=x.Length; j++)
{ for (int k=0; k<=x[j].Length; k++)
{
Console.WriteLine ("enter the"+(k+1)+"elements of the "+
(j+1)+"row");
x [j, k] = int.Parse (Console.ReadLine());
}
}
for (int j=0; j<=x.Length; j++)
{
Console.WriteLine ();
for (int k=0; k<=x[j].Length; k++)
{
Console.Write (x[j,k]+"\t");
}

Console.WriteLine ();
for (int j=0; j<=x.Length; j++)
{
for (int k=0; k<=x[j].Length; k++)
{ sum += x [j, k];
} }

Console.WriteLine ("The sum of all the elements are {0}",sum);

Console.ReadLine();

5. Write a Program in C# to demonstrate Boxing and Unboxing


using
using
using
using

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

namespace boxing
{

public struct Point


{
public int x, y;
public Point(int a, int b)
{
x = a;
y = b;
}
public void display()
{
Console.WriteLine("x={0}, y={1}", x, y);
}
}
class Program
{
static void Main(string[] args)
{
Point p1 = new Point(2, 3);
Console.WriteLine("DISPLAYINYING FOR STRUCT TYPES");
p1.display();
object o1 = p1;
Console.WriteLine(o1.GetType());
Point p2 = (Point)o1;
p2.display();
Console.WriteLine("DISPLAYINYING FOR PRIMITIVE TYPES");
Console.WriteLine("----------------------boxing-----------------------------------");
Int x = 10;
object o = (object)x; // Explicit Boxing
Console.WriteLine("The object o = {0}", o);
Console.WriteLine("---------------------Unboxing-----------------------------------");
object obj=20;
int j=int(obj);
Console.WriteLine("The unboxing is = {0}",j);
Console.ReadLine();
}
}}

6. Write a program in C# to implement Single Inheritance.


class a
{
public void display()
{
System.Console.WriteLine("good morning");
}
}
class b : a //b is child of a
{

public void display1()


{
System.Console.WriteLine("good noon");
}
}
class test
{
public static void Main()
{
b x=new b();
x.display();
x.display1();
}}
MultiLevel Inheritance
using System;
namespace Inherit
{
class Shape
{
public Shape()
{
Console.WriteLine("Constructor of base class Shape");
}
}
class Polygon : Shape
{
public Polygon()
{
Console.WriteLine("Constructor of Base class Polygon");
}
}
class Quad : Polygon
{public Quad(){
Console.WriteLine("Contructor of class Quad");
}
public static void Main(string[] args)
{
Quad obj= new Quad();
}}}

7.Demonstrate an interface with a C# program.


using System;
interfacecylinder
{
void area ();
}
class test:cylinder
{
void area()

{
double pi=3.142;
Console.WriteLine ("Enter the radius and height");
double r,h,res;
r = double.Parse (Console.ReadLine ());
h = double.Parse (Console.ReadLine ());
res = (2 *pi * r * h) + (2 * pi * r * r);
Console.WriteLine ("Area is"+res);
}
}
class MainClass
{
public static void Main (string[] args)
{
cylinder c=new test()
c.area();
Console.ReadLine();
}
}

8. Write a program in C# to demonstrate Operator overloading.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Complex
{
public int real;
public int imaginary;
int a, b, c;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public Complex(int x, int y, int z)

{
a = x;
b = y;
c = z;
}
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
public override string ToString()
{
return (String.Format("{0} + {1}i", real, imaginary));
}
public static Complex operator ++(Complex op1)
{
op1.a++;
op1.b++;
op1.c++;
return op1;
}
public void ShowTheResult()
{
Console.WriteLine(a + "," + b + "," + c);
Console.ReadLine();
}
public static void Main()
{
Complex num1 = new Complex(2, 3);
Complex num2 = new Complex(3, 4);

Complex c3 = new Complex(10, 20, 30);


c3++;
// overloaded plus operator:
Complex sum = num1 + num2;
// Print the numbers and the sum using the overriden ToString method:
Console.WriteLine("First complex number: {0}", num1);
Console.WriteLine("Second complex number: {0}", num2);
Console.WriteLine("The sum of the two numbers: {0}", sum);
c3.ShowTheResult();
Console.ReadLine();
}
}
8. Demonstrate Use of Virtual and override key words in C# with a simple program.
using System;
using System.Collections.Generic;

using System.Linq;
using System.Text;
namespace VIRTUAL
{
class shapes
{
public virtual void points()
{
Console.WriteLine("All the geo figures");
}
}
class hexagon : shapes
{
public override void points()
{
Console.WriteLine("hexa has 6 points");
}
}
class circle : shapes
{
public override void points()
{
Console.WriteLine("circle has 0 points");
}
}
class Program
{
static void Main(string[] args)
{
shapes []s={ new shapes(), new hexagon(),new circle()};
for(int i=0;i<s.Length;i++)
{
s[i].points();
}
Console.ReadLine();
}
}
}
8 c) Write a program to demonstrate abstract class and abstract methods in C#.
using System;
abstract class service
{
public abstract void detail();
}
class employee:service
{

String name;
int number, salary;
public override void detail()
{
Console.WriteLine("Enter employee name ");
name=Console.ReadLine();
Console.WriteLine ("Enter employee number");
number=int.Parse(Console.ReadLine());
Console.WriteLine ("Enter employee salary");
salary=int.Parse(Console.ReadLine());
Console.WriteLine ("Name\tnumber\tsalary");
Console.WriteLine (name + "\t" + number + "\t" + salary);
}
}

}
class test
{
public static void Main()
{

}}

employee b = new employee();


b.detail();

9. Write a program
C#(ENCAPSULATION).

to

illustrate

using System;
class Person
{
private string myName ="N/A";
private int myAge = 0;

public string Name


{
get
{
return myName;
}
set

the

use

of

different

properties

in

{
myName = value;
}
}
public int Age
{
get
{
return myAge;
}
set
{
myAge = value;
}
}
static int count=0;
public static int Count
{

get
{
count++;
return count;
}
}
public override string ToString()
{
return "Name = " + Name + ", Age = " + Age;
}
public static void Main()
{
Console.WriteLine ("USING GET AND SET PROPERTIES");
Person person = new Person();
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.WriteLine ("---------------------------------");
Console.WriteLine ("USING STATIC PROPERTIES");
Console.WriteLine(Person.Count);
Console.WriteLine(Person.Count);
Console.WriteLine(Person.Count);
}
}

9. Write a program in C# to demonstrate INDEXERS.


using System;
using System.Collections;
class MyClass
{

private string []data = new string[5];


public string this [int index]
{

get
{
return data[index];
}
set
{
data[index] = value;
}}

}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc[0] = "Rajesh";
mc[1] = "A3-126";
mc[2] = "Snehadara";
mc[3] = "Bang";
mc[4] = "Mumbai";
Console.WriteLine("{0},{1},{2},{3},{4}",mc[0],mc[1],mc[2],mc[3],mc[4]);
}}

10.
Write a program to implement CONSOLE
formatting, Console IO of both number & strings)
class StandardNumericFormats
{
static void Main()
{
Console.WriteLine("{0:C2}", 123.456);
Console.WriteLine("{0:D6}", -1234);
Console.WriteLine("{0:E2}", 123);
Console.WriteLine("{0:F2}", -123.456);
Console.WriteLine("{0:N2}", 1234567.8);
Console.WriteLine("{0:P}", 0.456);
Console.WriteLine("{0:X}", 254);
}
}
................................................
class CustomNumericFormats
{
static void Main()

I/O

OPERATIONS(Numerical

{
Console.WriteLine("{0:0.00}", 1);
Console.WriteLine("{0:#.##}", 0.234);
Console.WriteLine("{0:#####}", 12345.67);
Console.WriteLine("{0:(0#) ### ## ##}", 29342525);
Console.WriteLine("{0:%##}", 0.234);
}
}
...........................................
//FOR STRINGS.
class UsingReadLine
{
static void Main()
{
Console.Write("Please enter your first name: ");
string firstName = Console.ReadLine();
Console.Write("Please enter your last name: ");

string lastName = Console.ReadLine();


Console.WriteLine("Hello, {0} {1}!", firstName, lastName);
}
}
//FOR NUMBERS
class ReadingNumbers
{
static void Main()
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
double f = double.Parse(Console.ReadLine());
Console.WriteLine("{0} * {1} / {2} = {3}", a, b, f, a * b / f);
}
}

11. Using Try, Catch and Finally blocks write a program in C# to demonstrate error
handling.
using System;
namespace exceptionhandling
{
class MainClass
{
public static void Main (string[] args)
{
intnumbers = new int[2];
try
{
numbers[0] = 23;
numbers[1] = 32;
numbers[2] = 42;
foreach(int i in numbers)
Console.WriteLine(i);
}
catch(IndexOutOfRangeException ex)
{
Console.WriteLine("An index was out of range!\n"+ ex.Message);
}
catch(Exception ex)
{

Console.WriteLine("Some sort of error occured: " + ex.Message);


}
finally
{
Console.WriteLine("It's the end of our try block.");
}
Console.ReadLine();
}
}
}

12. Write a program to demonstrate of Simple delegates without events.


using System;
namespace delegatespgm
{
public delegate void methods();
class test
{
public void strconcat()
{
Console.WriteLine("enter the string1andstring2");
string s1=Console.ReadLine();
string s2=Console.ReadLine();
string s3 = s1 + s2;
Console.WriteLine ("STRING CONCAT IS" + s3+"\n");
}
public void strreplace()
{
string s3 = "Visual C# Express";
s3=s3.Replace("C#", "Basic");
Console.WriteLine ("STRING REPLACE IS" + s3+"\n");
}
public void strlower()
{
string s3 = "pesit bangalore";
s3=s3.ToLower();
Console.WriteLine ("STRING LOWER IS" + s3+"\n");
}
}

class MainClass
{
public static void Main (string[] args)
{
test t1 = new test ();
methods m=new methods(t1.strconcat);
m+=t1.strreplace;
m+=t1.strlower;
m();
} }}

Program on Events+Delegates.
using System;
namespace Myevents
{
public class eventtestclass
{
private int nvalue;
public delegate void delvalue();
public event delvalue changed;
protected virtual void callevent(){
if(changed!=null) changed();
else
Console.WriteLine("Event fired but no handler");
}
public eventtestclass(int n)
{ setvalue(n); }
public void setvalue(int nv)
{
if(nvalue!=nv)
{
nvalue=nv;
callevent();
}}
}
class program
{
static void Main()
{
eventtestclass etc=new eventtestclass(3);
etc.setvalue(5);
etc.setvalue(5);
etc.setvalue(3);
Console.ReadLine();
}}

Instructions to work with C#.NET


Download the Visual studio 2010 from Microsoft Website
Download VS2010Beta1ENU_PRO_2PartsTotal.part1.exe and
VS2010Beta1ENU_PRO_2PartsTotal.part2.rar files from here.
If you running setup file from a CD then open CD contents and click on setup.exe file
Take back up of VHD (Virtual Hard Disk) which is a Windows XP with Office 2007, Visual
Studio 2008 professional, and SQL Server 2005 Express edition, Silver light 2.0 SDK and
start installation by double clicking VS2010Beta1ENU_PRO_2PartsTotal.part1.exe. This is the
first screen you will see.

Once u click install it will extract the ISO image in the specified directory.

Once the ISO image is created, I mounded the Disk. This ISO image auto run will launch the
installation. This the first screen of the installation.

Click on the install Microsoft Visual Studio 2010. This will extract the setup in the files and
next u will see the following screen.

Click Next.

Accept the license terms and click next.

Select any of the check box, this will enable Customize button at the bottom left corner.
Select the customize button to select what components you want to install. If you select
both the check boxes all the components will be selected automatically.

If you want you can specify the path where this should be installed, but I am leaving as it is.
And click install

Be patient this will take looooooong timebecause this will install a looooooong list of
items
After installing Microsoft .Net framework .it will ask for a restart.Dont get panic please
go ahead and allow it restart the system. After restarting the system, installation will start
automatically. Once all the components were installed, you will get finish page.

Thats it. Click finish button. You are ready to explore the mush waited and fully loaded

visual Studio 2010.

Another way to work with C#


Monodevelop
Development - Getting Started
Its relatively easy to get started working on MonoDevelop, but this page aims to make it
easier to get off the ground.
If youre on OS X you can also try @dvdsgls one step
install: https://github.com/dvdsgl/monodevelop-build
Setting up an Environment
MonoDevelop doesnt require the very latest version of Mono, and we specifically depend on
GTK+ features no later that GTK+ 2.8. That said, using a recent release of Mono and Gtk#
is likely to improve reliability and performance.
It is strongly recommended to use a packaged release of Mono for your distribution,
as it is very easy to mix up conflicting Mono versions if installing from source. If you must
install Mono from source, set up a Parallel Mono Environment.
Make sure you have git installed, and check MonoDevelop out from GitHub.
Building and Installing
Open a terminal in the top-level MonoDevelop directory, and run
./configure --profile=core
It may fail because of missing dependencies; install them, and re-run the command.
There are a number of other profiles that can be used; the command
./configure --help
explains how they are used.
Next, use
make
to build MonoDevelop.
Since youre working on the development version, its best not to install it; instead, you can
use

make run
to run it without installing it.
It is a good idea to keep separate copies for using and developing.
If you do install MonoDevelop, it is best to run the current version uninstalled, to make sure
it works, before installing it.
Working on MonoDevelop
Before hacking on MonoDevelop, dont be afraid to ask questions on #monodevelop
IRC or MonoDevelop mailing list. People will be able to give you pointer about where to start
and how best to approach the problems your are trying to solve. There are also number
ofArticles on the MonoDevelop architecture and on implementing addins.
The MonoDevelop solution can be opened from MonoDevelop, and builds can be preformed
form within MonoDevelop. Indeed, some parts of the build (such as Stetic code generation)
must be performed within MD. However, the modified MonoDevelop must be run from a
terminal with
make run
You should follow our contribution rules, for code style and licensing.
After you have made your changes, commit them with a descriptive message and open a
pull request on GitHub.
Troubleshooting the Build
If the MonoDevelop build fails, there are a number of possible fixes.
If the build commands failed, try a clean rebuild:
make clean; make
and fix any that are in conflict, or delete any that have changed unnecessarily.
If the build system failed, check for changed files and re-run the configure script.

How to execute a program in C#.NET either in


Visual Studio
Or MonoDevelop

Visual Studio

1. Open Visual Studio i.e. Click Start->Programs->Microsoft Visual


Studio 2010->Microsoft Visual Studio 2010.
2. Visual Studio Interface will open up and you will get a start page.
3. Click on New Project.
4. From Template Pane, select Visual C#, select console application
5. Visual studio will create a console application project with default
name like consoleapplication1
6. Click ok after you give name of the console application (if you
want to change from default).
7. Type in the program in the default editor what you get

8. Save the program.


9. To run the program first you need to compile it. To compile the
program, select build menu and click on build solution. If there are
no errors, you will get a message build successful.
10. If compilation is successful, you can execute the program by
clicking debug menu, Start Debugging or Start without Debugging.

MonoDevelop

Open Ubuntu software center and type mono in the search box,now choose MonoDevelop package in the
list and Install.
In Terminal,

sudo apt-get install monodevelop

After the installation start MonoDevelop,you should see an aesthetic programming environment.

To start programming select


File -> New -> File..
Select C# and general
Build the program:press F7
Run the program:ctrl+F5

NOTE:This is very important the console in MonoDevelop 2.4 does not read input.This is a bug in mono
and has already been reported.To execute programs with ReadLine statements please follow the
following steps:
After installing MonoDevelop
Create the program using Vim editor,
vim Demo1.cs

Now install a package called mono-mcs,which is a c# compiler,


sudo apt-get install mono-mcs

Compiling the program and generating .exe file,


mcs Demo1.cs

Executing the program,


mono Demo1.exe

Potrebbero piacerti anche