0% found this document useful (0 votes)
35 views19 pages

C# - Ii Unit

Ushahaa Jsjsjsjs

Uploaded by

akshayamith887
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views19 pages

C# - Ii Unit

Ushahaa Jsjsjsjs

Uploaded by

akshayamith887
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

C# - II UNIT

Two Mark Questions


1. List types of constructors in C#?
• Default Constructor
• Parameterized Constructor
• Copy Constructor
• Private Constructor
2. What do you mean by overloaded constructors?
Constructor Overloading is a technique to define multiple constructors within a class
with different sets of parameters to achieve polymorphism. Constructors are methods invoked
when an object is created. A user can implement constructor overloading by defining two or
more constructors in a class sharing the same name. This is done by declaring the
constructors with different parameter lists.
3.What are Static constructors?
A static constructor is used to initialize any static data, or to perform a particular
action that needs to be performed only once. It is called automatically before the first instance
is created or any static members are referenced.
4.What do you mean by polymorphism?
Polymorphism means ‘one name, many forms’. It is the capability of one object to
behave in multiple ways. In other words, one object has many forms or has one name with
multiple functionalities. Polymorphism provides the ability to a class to have multiple
implementations with the same name.
5.What do you mean by copy constructor?
A constructor that creates an object by copying variables from another object or that
copies the data of one object into another object is termed as the Copy Constructor. It is a
parameterized constructor that contains a parameter of the same class type.
6.What do you mean by destructors? How they are defined in C#?
A destructor works opposite to constructor, it destructs the objects of classes. It is a method
called when an object is no more required. It can be defined only once in a class.
The name of the destructor is the same as the class name and is preceded by a tilde(~).
Example:
class Car
{
~Car() // destructor
{
// cleanup statements...
}
}
7.What do you mean by “this” reference in C#?
The this keyword is used to reference the current instance of a class, or an object
itself. It is also used to differentiate between method parameters and class fields if they both
have the same name. You can also use the keyword to call another constructor from a
constructor in the same class.
8.Differentiate constant member & read-only members used in C#.
Constant Member Read-only Member
Declared using the const keyword. Declared using the readonly keyword.
Only the class level fields or variables can Only the class level fields can be readonly.
be constant. The local variables of methods cannot be
readonly.
The constant fields must be initialized at the Readonly fields can be initialized at
time of declaration. declaration or in the constructor.
Therefore, const variables are used for Therefore, readonly variables are used for
compile-time constants the run-time constants.

9. Give the syntax and example for interface in C#.


Syntax:

interface <interface_name >


{
// declare Events
// declare indexers
// declare methods
// declare properties
}

Example:
interface Animal
{
void animalSound(); // interface method (does not have a body)
void run(); // interface method (does not have a body)
}

10. What is operator overloading ?


A user-defined type can overload a predefined C# operator. That is, a type can
provide the custom implementation of an operation in case one or both of the operands are of
that type. An operator can be overloaded by defining a function to it. The function of the
operator is declared by using the operator keyword.
11. List any four operators that cannot be overloaded.
+= -= *= /= %=
The assignment operators cannot be overloaded.
12. Give the syntax of defining operator function.
public static classname operator op (parameters)
{
// Code
}

For Unary Operator


public static classname operator op (t)
{
// Code
}
For Binary Operator
public static classname operator op (t1, t2)
{
// Code
}

13. What is a Delegate ? What is it used for?


A delegate is a type that represents references to methods with a particular parameter
list and return type. When you instantiate a delegate, you can associate its instance with any
method with a compatible signature and return type. You can invoke (or call) the method
through the delegate instance.
Delegates are used to pass methods as arguments to other methods. Event handlers are
nothing more than methods that are invoked through delegates.
14. What is delegate method?
The methods whose references are encapsulated into a delegate instance are known as
delegate methods. The signature and return type of delegate methods must exactly match the
signature and return type of the delegate.
15. List the steps involved in creating and using a delegate.
• Delegate declaration
• Delegate method declaration
• Delegate instantiation
• Delegate invocation

16. What is an Event in C# ? Give the syntax of event declaration.


An event is a delegate type class member that is used by the object or class to provide
a notification to other objects that an event has occurred. The client object can act on an event
by adding an event handler to the event.
Syntax:
modifier event type event-name
17. List any four built in exceptions in C#.
• StackOverflowException
• ArithmeticException
• ValidationException
• ArgumentException
18. What is use of finally() block in exception handling ?
Finally() block is used to execute a given set of statements, whether an exception is
thrown or not thrown. It always executes whether the try block terminates normally or
terminates due to an exception. It is used to execute clean up code like closing files, or freeing
up threads, as it executes regardless of an exception.
19. What is VB IDE?
Visual Studio is a powerful and customizable programming environment that contains all the
tools you need to build programs quickly and efficiently. It offers a set of tools that help you
write and modify the code for your programs, and also detect and correct errors in your
programs.
20. List any four components of VB IDE.
• Toolbar
• Menu bar
• Properties Window
• Solution Explorer
21. What do you mean by properties in VB.net?
A property is a value or characteristic held by a Visual Basic object. Properties can be
set at design time by using the Properties window or at run time by using statements in the
program code.
22. What is Intellisence? List any two features.
IntelliSense is a code-completion aid that attempts to guess what the developer wants to type
in order to complete a line of code.
Features:
• Complete Word
• Automating Brace matching.

23. What is the significance of component tray?
The Component Tray shows icons for nonvisual items in the designer. It provides a way for
users to access and set the properties of those items. Some types of components, such as a
Timer, may not have a user interface that can be viewed at design time.
24. List any four tools available in toolbox.
• Text Box
• Label
• Button
• Combo Box

Long Answer Questions ( 4/5/6 Marks)


1.With syntax and example, explain how class is defined and used in a program.
In C#, A class definition starts with the keyword class and contains the class name. It also
includes the attributes and modifiers of the class as well as its interfaces. Then the class body
is provided within curly braces.
Syntax:
AccessSpecifier class NameOfClass
{
// Member variables
// Member functions
}
To access the class members, you will use the dot (.) operator. The dot operator links the
name of an object with the name of a member.
In the above syntax, AccessSpecifier provides the access specifier for the class. Then the
keyword class is used which is followed by the NameOfClass. Then the class body is
provided.
To access the class members, you will use the dot (.) operator. The dot operator links the
name of an object with the name of a member.
Example:
class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}
2. Explain concept of Static members and methods with example?
Static member: We can define class members as static using the static keyword. When we
declare a member of a class as static, it means no matter how many objects of the class are
created, there is only one copy of the static member. The static member is callable on a class
even when no instance of the class has been created. The static member is always accessed by
the class name, not the instance name.
Static methods: A static method is declared with the help of static keyword. Static methods
are accessed with the name of the class. A static method can access static and non-static
fields, static fields are directly accessed by the static method without class name whereas
non-static fields require objects.
using System;
class Students
{
static public int t = 55; // Creating static method
public static void total()
{
Console.WriteLine(“Total number of students in our class:”+ t);
}
}
public class GFG // Driver Class
{
static public void Main() // Main Method
{
// Accessing the static method using its class name
Students.total();
Console.ReadKey();
}
}

3.What is Constructor? Explain any 2 types of constructors in C#?


A constructor is a special method of the class which gets automatically invoked whenever an
instance of the class is created. Like methods, a constructor also contains the collection of
instructions that are executed at the time of Object creation. It is used to assign initial values
to the data members of the same class. Constructor name must be the same as its class name.
A constructor must have no return type.

Two types:
• Default constructor
• Parameterized constructor

(i) Default Constructor:


A constructor without any parameters is called a default constructor. If we do not create
constructor the class will automatically call default constructor when an object is created.

Example:
using System;
public class Employee
{
public Employee() //constructor
{
Console.WriteLine("Default Constructor Invoked");
}
public static void Main(string[] args)
{
Employee e1 = new Employee();
Employee e2 = new Employee();
}
}
Output:
Default Constructor Invoked
Default Constructor Invoked

(ii) Parameter Constructor:

A constructor having at least one parameter is called as parameterized constructor. It can


initialize each instance of the class to different values.

Example:

using System;
class Geek {
// data members of the class.
String name;
int id;
Geek(String name, int id) //ParameterizedConstructor
{
this.name = name;
this.id = id;
}
public static void Main() // Main Method
{
Geek geek1=new Geek("GFG",1); //invoking parameterized constructor
Console.WriteLine("GeekName = " + geek1.name +
" and GeekId = " + geek1.id);
}
}

Output:
GeekName = GFG and GeekId = 1

4. Write a note on constructor overloading?


It is the ability to redefine a Constructor in more than one form. A user can implement
constructor overloading by defining two or more constructors in a class sharing the same
name. C# can distinguish the constructors with different signatures. i.e. the constructor
must have the same name but with different parameters list. We can overload constructors
in different ways as follows:
• By using different type of arguments
• By using different number of arguments
• By using different order of arguments
During compilation of the code, the compiler compares the signature used for the new
object to those available in the class. If there is a perfect match, the corresponding
constructor is used.

Example:

using System;
class Car {

Car() // constructor with no parameter


{
Console.WriteLine("Car constructor");
}

Car(string brand) // constructor with one parameter


{
Console.WriteLine("Car constructor with one parameter");
Console.WriteLine("Brand: " + brand);
}

static void Main(string[] args)


{
Car car1 = new Car(); // call with no parameter
Console.WriteLine();
Car car2 = new Car("Bugatti"); // call with one parameter
Console.ReadLine();
}
}

5. Explain Multi-Level inheritance with example.

When one class inherits another class which is further inherited by another class, it is
known as Multi-level Inheritance. For example, three classes called A, B, and C, as shown
in the below image, where class C is derived from class B and class B, is derived from class
A. In this situation, each derived class inherit all the characteristics of its base classes. So
class C inherits all the features of class A and B

Syntax:

class A
{
…..
}
Class B : A //first level derivation
{
…..
}
Class C : B //second level derivation
{
…..
}
Example:
using System;
public class Animal
{
public void eat() { Console.WriteLine("Eating..."); }
}
public class Dog: Animal //first level derivation
{
public void bark() { Console.WriteLine("Barking..."); }
}
public class BabyDog : Dog //second level derivation
{
public void weep() { Console.WriteLine("Weeping..."); }
}
class TestInheritance2
{
public static void Main(string[] args)
{
BabyDog d1 = new BabyDog();
d1.eat();
d1.bark();
d1.weep();
}
}

Output:
Eating...
Barking...
Weeping...

6. Write note on class member visibility?


The visibility of a class, a method, a variable or a property tells us how this item can be
accessed. The most common types of visibility are private and public, but there are actually
several other types of visibility within C#.
public - the member can be reached from anywhere. This is the least restrictive visibility.
Enums and interfaces are, by default, publicly visible.
protected - members can only be reached from within the same class, or from a class which
inherits from this class.
protected internal - the same as internal, except that classes which inherit from this class can
reach its members; even from another project.
private - can only be reached by members from the same class. This is the most restrictive
visibility. Classes and structs are by default set to private visibility.

So for instance, if you have two classes: Class1 and Class2, private members from Class1 can
only be used within Class1. You can't create a new instance of Class1 inside of Class2, and
then expect to be able to use its private members.

If Class2 inherits from Class1, then only non-private members can be reached from inside of
Class2.
7. What is Interface? Explain the defining , extending and implementing interface.

Interface in C# is a blueprint of a class. It is like abstract class because all the methods
which are declared inside the interface are abstract methods. It cannot have method body and
cannot be instantiated. Any class that implements the interface will provide an implementation
of the members defined in the interface.

Defining Interfaces
Interfaces define properties, methods and events, which are the members of the interface.
Interfaces contain only the declaration of the members. It is the responsibility of the deriving
class to define the members.

Syntax:
interface InterfaceName
{
Member declarations;
}

Extending an Interface
Like classes, interfaces can also be extended. An interface can be sub interfaced from
other interfaces. The new sub interface will inherit all the members of the super interface.
Syntax:
interface name2 : name1
{
Members of name2
}

Implementing an Interface
Interfaces are used as super classes whose properties are inherited by classes. It is
therefore necessary to create a class that inherits the given interface.

Syntax:
class classname : interface name
{
Body of classname
}

Example:
using System;
interface IPolygon
{
void calculateArea(int l, int b); // method without body
}
class Rectangle : IPolygon
{
public void calculateArea(int l, int b) // implementation of methods
{
int area = l * b;
Console.WriteLine("Area of Rectangle: " + area);
}
}
class Program{
static void Main(string[] args){

Rectangle r1 = new Rectangle();


r1.calculateArea(100, 200);
}
}

8. Write a note on rules for overloading unary and binary operators.


Operator overloading gives the ability to use the same operator to do various operations. It
provides additional capabilities to C# operators when they are applied to user-defined data
types.
Syntax:
public static classname operator op (parameters)
{
// Code
}

Unary Operator Overloading:

The general forms of operator overloading in the case of unary operator follows the syntax
given below.

public static classname operator op (t)


{
// Code
}

Here, the return type can be anything, but it should not be void for the operators like +,-,
~ and .(dot). The return type of this operator should be either an integer or a Boolean type. It
is important to note that the Boolean operators roll out true and false and hence can be
overloaded only as pairs. A compilation error would occur if not done because a class generally
declares this operator without declaring the other.

Binary Operator Overloading:


To overload a binary operator, you must seek two arguments. You need to ensure that one of
the operators should be of type class or struct where the operator is defined. A binary
operator cannot return void, but it can return all other types of values while implementing
overloading.
Syntax:
public static classname operator op (t1, t2)
{
// Code
}
It is important to keep a note that operators such as ==. !=, <>, <=, >= are only overloaded as
pairs. When a binary arithmetic operator is overloaded using them, the assignment operators
will automatically get overloaded. For instance, if you overload the + operator, it gets
implicitly overloaded as += operator too.

9. Explain Unary operator overloading with example.

The general forms of operator overloading in the case of unary operator follows the syntax
given below.

public static classname operator op (t)


{
// Code
}

Here, the return type can be anything, but it should not be void for the operators like +,-,
~ and .(dot). The return type of this operator should be either an integer or a Boolean type. It
is important to note that the Boolean operators roll out true and false and hence can be
overloaded only as pairs. A compilation error would occur if not done because a class generally
declares this operator without declaring the other.

Example:

using System;
namespace Calculator {

class Calculator {
public int number1 , number2;
public Calculator(int num1 , int num2)
{
number1 = num1;
number2 = num2;
}

// Function to perform operation by changing sign of integers


public static Calculator operator - (Calculator c1)
{
c1.number1 = -c1.number1;
c1.number2 = -c1.number2;
return c1;
}
public void Print() // Function to print the numbers
{
Console.WriteLine ("Number1 = " + number1);
Console.WriteLine ("Number2 = " + number2);
}
}

class EntryPoint{
static void Main(String []args) {

// using overloaded – operator with the class object


Calculator calc = new Calculator(15, -25);
calc = -calc;
calc.Print(); // To display the result
}
}}

Output:
Number1 = -15
Number2 = 25

10. Explain binary operator overloading with example.


To overload a binary operator, you must seek two arguments. You need to ensure that one of
the operators should be of type class or struct where the operator is defined. A binary
operator cannot return void, but it can return all other types of values while implementing
overloading.
Syntax:
public static classname operator op (t1, t2)
{
// Code
}

Example:
using System;
namespace BinaryOverload {
class Calculator {
public int number = 0;
public Calculator() {} // no-argument constructor
public Calculator(int n) // parameterized constructor
{
number = n;
}
// Overloading of Binary "+" operator
public static Calculator operator + (Calculator Calc1,Calculator Calc2)
{
Calculator Calc3 = new Calculator(0);
Calc3.number = Calc2.number + Calc1.number;
return Calc3;
}
public void display() // function to display result
{
Console.WriteLine("{0}", number);
}
}

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

Calculator num1 = new Calculator(200);


Calculator num2 = new Calculator(40);
Calculator num3 = new Calculator();
num3 = num1 + num2;
num1.display(); // Displays 200
num2.display(); // Displays 40
num3.display(); // Displays 240
}
}
}
Output:
200
40
240
It is important to keep a note that operators such as ==. !=, <>, <=, >= are only overloaded as
pairs. When a binary arithmetic operator is overloaded using them, the assignment operators
will automatically get overloaded. For instance, if you overload the + operator, it gets
implicitly overloaded as += operator too.

11. Explain with syntax and example, how delegates are declared.
Delegate type can be declared using the delegate keyword. Once a delegate is declared,
delegate instance will refer and call those methods whose return type and parameter-list
matches with the delegate declaration.
Syntax:
modifier delegate return-type delegate-name (parameter list);
• The delegate key word represents that the declaration represents a class type derived
from System.Delegate.
• The return type indicates the return type of the delegate.
• Parameter list contains the parameters which are required by the method when called
through the delegate. Parameters identify the signature of the delegate.
• The delegate-name is any valid C# identifier and represents the name of the delegate that
will be used to instantiate the delegate objects.
• The modifier controls the accessibility of the delegate. Delegates can take the following
modifiers i.e. new, public, private, protected and internal.
A delegate may be defined in the following places:
✓ Inside a class
✓ Outside a class
✓ As a top level object in a namespace
Example:
public delegate int GeeksForGeeks (int G, int F, int G);

public is the modifier


int is return type
GeeksForGeeks is delegate name
(int G, int F, int G) are the parameters

12. Write note on delegate methods.


The methods whose references are encapsulated into a delegate instance are known as
delegate methods. The signature and return type of delegate methods must exactly match the
signature and return type of the delegate.
For instance, the delegate
delegate string GetAString()
can be made to refer to the method ToString() using an int object N as follows:
int N = 100;
GetAString s1 = new GetAString(N.ToString);
The delegate
delegate void Delegate1();
can encapsulate references to the following methods:
public void F1() //instance method
{
Console.WriteLine(“F1”);
}
static public void F2() //static method
{
Console.WriteLine(“F2”);
}
Similarly, the delegate
Delegate double MathOp(double x,double y);
can refer to any of the following methods:
public static double Multiply(double a, double b)
{
return (a*b);
}
public double Divide(double a, double b)
{
return (a/b);
}
In both the cases, the signature and return type of methods match the signature and type of
the delegate.
13. Write a note on delegate instantiation and invocation.
After declaring a delegate, a delegate object is created with the help of new keyword. Once a
delegate is instantiated, a method call made to the delegate is pass by the delegate to that
method.
Syntax:
delegate_name instance_name = new delegate_name (method_name);

The parameters passed to the delegate by the caller are passed to the method, and the return
value, if any, from the method, is returned to the caller by the delegate. This is known as
invoking the delegate.
Syntax:
delegate_object (parameters list)
Example:
using System;
delegate int Calculator(int n); //declaring delegate

public class DelegateExample


{
static int number = 100;
public static int add(int n)
{
number = number + n;
return number;
}
public static int getNumber()
{
return number;
}
public static void Main(string[] args)
{
Calculator c1 = new Calculator(add); //instantiating delegate
c1(20); //invoking delegate
Console.WriteLine("After c1 delegate, Number is: " +getNumber();

Console.ReadKey();
}
}

14. With syntax and example explain exception handling mechanism in C#.
C# exception handling is built upon four keywords:

• try − This block holds the code that may throw an exception. It is followed by one or
more catch blocks.
• catch − This block catches the exception thrown by the try block. The catch keyword
indicates the catching of an exception.
• finally − The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed
whether an exception is raised or not.
• throw − A program throws an exception when a problem shows up. This is done
using a throw keyword.

Syntax:

try {
// statements causing exception
}
catch ( ExceptionName e1 ) {
// error handling code
}
catch ( ExceptionName e2 ) {
// error handling code
}
finally {
// statements to be executed
}

Example:
class Program{
static void Main(string[] args)
{
try
{
int num = 0;
int result = 100 / num; //exception occurs
Console.WriteLine( result);
}
catch (DivideByZeroException e)
{
Console.WriteLine(e); //exception caught by catch block
}

finally //executes irrespective of exception


{
Console.Write("Finally must be executed");
}
Console.ReadKey();
}}

15. Explain following components of VBIDE.


i) Project Explorer
The docked on the right side of the screen and just below standard tool bar, is the project
explorer window. It serves as a quick reference to the various element of a project namely
form, class and module. All the objects that make up the application are packed in a project.
ii) Toolbox
The Tool box contains the icon of the control we can place on a form to create the
application’s user interface. Controls are elements that provide the user interface. Controls
are tools such as text box, button, label and other objects that can be dragged and drawn on a
form to perform certain tasks according to the events associated with them.

iii) Properties Window


The properties of the objects are displayed in the Properties Window. It allows us to assign or
change properties associated with a particular object. All the characteristics of an object are
called its properties. Properties are attributes such as size, position etc. like a form, each
control has its own set of properties.

16. Explain following components of VBIDE


i) Code window
The place where the code is written is Code Window. To open
the code window of a particular object, just double click on that object. Visual basic code
window consist of two list boxes - Object list box that allows us to select event procedure
associated with a particular object and Procedure list box that allows us to select the event
procedure associated with a particular type of event.

ii) Solution explorer


It contains a list of the items in the current solution. It displays a hierarchy-with the solution
at the top of the hierarchy, the projects one step down in the hierarchy, and the items in each
project as the next step down.
iii) Component tray
The component tray is a rectangular region displayed at the bottom of the design view
window while in design view mode, once it is active. It shows icons for nonvisual items in
the designer. It provides a way for users to access and set the properties of those items. Some
types of components, such as a Timer, may not have a user interface that can be viewed at
design time.

17. Explain following components of VBIDE


i ) Graphical Designers
When you're working on a project that has user interface elements-such as forms, VB.NET
can display what those elements will look like at run time. For example, when you're looking
at a Windows form, you're actually looking at a Windows form designer, and you can
manipulate the form, as well as add controls to it and so on.
There are several different types of graphical designers, including:
● Windows form designers
● Web form designers
● Component designers
● XML designers

ii) Dynamic Help window


The Dynamic Help window displays links to help topics, dynamically updated as you enter
code or move around the environment. It looks things up for you automatically. You can see
the Dynamic Help window by clicking the Dynamic Help tab under the Properties window

You might also like