Tutorial I
1. Find errors, if any in the following classdefinitions:
a) Class Vector (int x,y};
Ans:
Opening braces { is not given
b) Class ABC
{
public int x;
protected private y;
}
Ans:
Datatype is not specified for y.
c) Class xyz
{
public const int x;
public static int y;
}
Ans:
Value for constant variable x is not specified.
d) Class ABC
{
int x=1;
int y=x+1;
}
Ans:
No error in initialization
e) Class ABC
{
static int x=1,y,z=2;
new double p=2.5;
}
Ans:
Error access modifier cannot be new
2.What is wrong with the following code?If it is correct,what does it produce?
Class A
{
static bool b1;
int m1;
public static void Main()
{
A a=new A();
Console.WriteLine(“b1=”+b1);
Console.WriteLine(m1=”+m1);
}
}
Ans:
The class variables should only accessed with instance of class.
3Find errors in the following class definition.
Class alpha
{
int x;
static int y;
static void F()
{
x=10;
y=20;
}
Static a1=new Alpha();
{
a1.x=100;
a1.y=200;
Alpha.x=0;
Alpha.y=0;
. …………..
……………
}
}
Ans:
Static variables are aways accessed using the class name and not the objects.
4.What is wrong with the following code?
Class xy
{
int x=0;
int y=x+1;
}
Ans:
Error in initialization.
5.What would be the output of the following code?
Class AB
{
int x=0;
public Void F()
{
int x=10;
Console.WriteLine(x);
}
}
Ans:
since X is not public to class AB
Method F() uses only value in it.
6.Comment on the following code:
Class AB
{
private int number;
public int number;
{
get{return number;} /* get property defines get accessor
method */
}
public int number
{
set{number=value;} /* set property defines set accessor
method */
}
}
7.Consider the following code:Will it compile?If not,why?
Class product
{
public static void Main()
{
int x=10,y=20;
Console.WriteLine(mul(x,y));
}
int mul( int a,int b) //if this is having access modifier as
public,this method will be invoked in main ()
function
{
return(a*b);
}
}
8.Will the following code compile?If no,why?
Class A
{
public static void Main()
{
Test t;
T.print();
}
}
Class Test // This class should be specified as public .also it will be
error
{
public void print()
{}
}
9.Create a class named integer to hold two integer values. Design a method swap
that could take two integer objects as parameters and swap their contents. Write a main
program to implement the class integer and the method swap.
using System;
Class Integer
{
public int a;
public int b;
public int temp;
public void swap(int x,int y)
{
a=x;
b=y;
temp=a;
a=b;
b=temp;
}
public static void Main()
{
integer i =new Integer();
int a=100;
int b=200;
I.swap(a,b);
Console.WriteLine(“After swapping:”);
Console.Writeline(“a=+a);
Console.WriteLine(“b=”+b);
}
}
Ans:
After swapping:
a=200
b=100