21
1 1 CS2041 / CS706 - C# and .NET Framework (Elective III) VII-Sem-IT 2008-Regulations TWO MARK Question & Answers -------------------------------------------------------------------------------------------- UNIT-I 1) Define a) Problem Domain b) Solution Domain Solving a problem involves conversion of problem domain or problem space to Solution domain. The problem domain is a sector or sectors to which the problem belongs. It is an area of interest having clearly defined boundaries. It forms an autonomous body describing high level features. The Solution domain is the subject matter that is of concern to the computer system and the implementor of the system. It describes the features in a manner which can be understood by the computer. The problem domain refers to the scope of the problem being addressed by the software system. While solving a problem using a computer ,its solution is in the form of a program. 2) Define in brief Object Oriented Principles. OOP is based on three key principles: encapsulation, inheritance, and polymorphism. 1. Encapsulation binds together code and data. 2. Inheritance is the mechanism by which one class can inherit the functionality of another. 3. Polymorphism lets you define one interface that describes a general set of actions. These attributes work together in a powerful way that enables the construction of reliable, reusable, and extensible programs. 3) Define a)Abstraction b)Encapsulation a) The essential features of an entity is known as abstraction. A feature may be either an attribute reflecting a property(or state or data) or an operation reflecting a method( or a behavior or function). Abstraction defines necessary and sufficient description rather than implementation. An inteterface is an abstraction and is the separation of an interface and its implementation is an example of abstraction. b) From the user’s point of view ,a number of features are packaged in a capsule to form an entity. This entity offers a number of services in the form of interfaces by hiding the implementation detail. The adcantages of encapsulation are a) Information hiding b) Implementation independence 4) Differentiate an interface from its implementation. Slno Interface Implementation 1 It is user’s view point. (What part) It is supplier’s view point. (How part) 2 It is used to interact with the outside world It describes how the delegated responsibility is carried out. 3 User is permitted to access the interfaces only Functions or methods are permitted to access the data. 4 It encapsulates the knowledge about the object. It provides the restriction of access data by the user. www.csetube.in

Cnf Unit-i - 2 Marks Csetube

Embed Size (px)

DESCRIPTION

c##

Citation preview

Page 1: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

1

1

CS2041 / CS706 - C# and .NET Framework (Elective III)

VII-Sem-IT 2008-Regulations

TWO MARK Question & Answers

-------------------------------------------------------------------------------------------- UNIT-I

1) Define a) Problem Domain b) Solution Domain

Solving a problem involves conversion of problem domain or problem space to Solution domain.

The problem domain is a sector or sectors to which the problem belongs. It is an area of interest having clearly

defined boundaries. It forms an autonomous body describing high level features.

The Solution domain is the subject matter that is of concern to the computer system and the

implementor of the system. It describes the features in a manner which can be understood by the computer.

The problem domain refers to the scope of the problem being addressed by the software system. While

solving a problem using a computer ,its solution is in the form of a program.

2) Define in brief Object Oriented Principles.

OOP is based on three key principles: encapsulation, inheritance, and polymorphism.

1. Encapsulation binds together code and data.

2. Inheritance is the mechanism by which one class can inherit the functionality of another.

3. Polymorphism lets you define one interface that describes a general set of actions.

These attributes work together in a powerful way that enables the construction of reliable, reusable, and

extensible programs.

3) Define a)Abstraction b)Encapsulation

a) The essential features of an entity is known as abstraction. A feature may be either an attribute

reflecting a property(or state or data) or an operation reflecting a method( or a behavior or function).

Abstraction defines necessary and sufficient description rather than implementation.

An inteterface is an abstraction and is the separation of an interface and its implementation is an

example of abstraction.

b) From the user’s point of view ,a number of features are packaged in a capsule to form an entity.

This entity offers a number of services in the form of interfaces by hiding the implementation detail.

The adcantages of encapsulation are a) Information hiding b) Implementation independence

4) Differentiate an interface from its implementation.

Slno Interface Implementation

1 It is user’s view point. (What

part)

It is supplier’s view point.

(How part)

2 It is used to interact with the

outside world

It describes how the delegated

responsibility is carried out.

3 User is permitted to access the

interfaces only

Functions or methods are

permitted to access the data.

4 It

encapsulates the knowledge

about the object.

It provides the restriction of

access data by the user.

www.csetube.in

Page 2: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

2

2

5) Define a) Class b) Object

A group of objects sharing common structure and behavior is called a class. A class is

a template for creating objects.

An object is an instance of a class. An object has identity,state and behavior.

A C# program is basically a collection of classes. A class is defined by a set of declaration statements

and methods containing instructions known as executable statements.

6) Differentiate an Object and a Class.

A class is a template for creating an object. An object is an instance of a class. An object

has memory and reference.

The class is C#'s basic unit of program functionality. However, it is more than that. It is also C#'s

foundation for object-oriented programming (OOP)

7) What are the advantages of OOP?

Code reuse

Seamless transition from different phases of s/w development

Modularity

8) What are the applications of C# ?

1) console applications

2) Winows applications

3) Developing windows controls

4) Developing ASP.NET projects

5) Creating Web Controls

6) Providing web services

7) Developiong .NET component library

9) What is .NET Framework?

o .NET represents an advanced new generation of software that will drive the Next

Generation Internet. Its purpose is to make information available any time, any place,

and on any device.

o Quick Definition

.NET is an initiative to integrate all Microsoft products with the “Next

Generation” web.

o .NET is a software framework that includes everything requiered for developing

software for web services. It integrates presentation technologies,component

technologies,and data technologies on a single platform so as to enable users to develop

internet applications as easily as thyey do on desktop systems.

o In brief .NET platform provides a new environment for creating and running

robust,scalable and distributed applications over the web.

o It consists of three distinct technologies

a)Common Language Runtime

o Framework base classes

o User and program Interfaces(ASP.NET and Winforms)

www.csetube.in

Page 3: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

3

3

10) State the Charateristics of C#.

a) Simple – C# simplifies C++ by eliminating irksome operations such as →,:: and pointers

b) Consistent – C# supports unified type system

c) Modern – Automatic garbage Collection

Modern approach to debugging

Rich intrinsic model for error handling

Decimal data type for financial applications

Robust security model

d) Object Oriented

Supports encapsulation,Inheritance, and Polymorphism

In C#,every thing is an object. There is no global functions,variables and constants

e) Type Safe – promotes robust programs

Following are some type safe measures :

i. All dynamically allocated objects and arrays are initialized to zero

ii. Use of uninitialized variables produces an error message by the compiler

iii. Access to arrays are range checked and warned if it goes out-of bounds

iv. C# does not permit unsafe casts

v. C# enforces overflow checking in arithmetic operations

vi. Reference paramets that are passed are type-safe

vii. C# supports automatic garbage collection

f) C# is versionable – Making new versions of software modules work with existing applications

is known as versioning. C# provides support for versioning with the help of new and override

keywords. Using versioning,a programmer can guarantee that his new class library will maintain

binary compatibility with the existing client applications.

g) Compatible - C# enforces the .NET common Language specifications and therefore allows

inter-operation with other .NET languages. C# provides support for transparent acces to COM

and OLE automation

h) Interoperability – C# provides support for using COM objects

11) Write the compilation and execution commands of a C# source program.

Overview of a C# Program

Hello, world

The canonical “Hello, world” program can be written in C# as follows:

www.csetube.in

Page 4: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

4

4

using System;

class Hello

{

static void Main()

{

Console.WriteLine(“Hello, world”);

}

}

Compiling and Running the Application

The default file extension for C# programs is .cs, as in hello.cs. Such a program can be

compiled with the command line directive

csc hello.cs

Which produces an executable program named hello.exe. The output of the program is:

Hello, world

12) What are tokens? What are the tokens supported in C# Language?

The smallest, non execuatable ,textual elements in a program are refered to as tokens. The compiler

recognizes them by building up expressions and statements.

In simple sterms,a C# program is a collection of tokens. C# includes the following five types of

tokens :

Keywords

Identifiers

Literals

Operators

Punctuators

Keywords are essential part of language definition. They implement specific features of the

language. They are reserved,and cannot be used as identifiers except when they are prefacedby

the @ character.

Few C# keywords are :

bool float namespace static

byte for new string

char foreach private this

catch finally override throw

13) What are Identifiers?

Identifiers are programmer-designed tokens. They are used for naming

classes,methods,variables,labels,namespaces,interfaces etc.

The rules for defining identifiers are :

www.csetube.in

Page 5: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

5

5

a) They have alphabets,digits and underscore characters.

b) They must not begin with a digit.

14) What are Escape Sequences? Enumerate differenct Esc Sequences.

Escape sequences are special backslash character constants that are used in output methods. For

example '\n' stands for a newline character.

The following tables lists the common Escape Sequences used in C#.

Literal

constant

Meaning

'\a' alert

'\b' Back space

'\f' Form feed

'\n' New line

'\r' Carriage return

'\t' Horizontal tab

'\v' Vertical tab

'\'' Single quote

'\''' Double quote

'\\' Back slash

'\o' null

15) Explain the difference between a Value type and reference type. Illustrate with some

examples

Value types:

* Value types can be created at compile time.

* Stored in stack memory.

* Garbage collector can't access the stack

* value types holds the data directly

* No default values will be stored in value types

* Examples for value types: Predefined datatypes,structures,enums

Reference types:

* Reference types can be created at run time.

* Stored in heap memory

* Garbage collector can access heap

* Reference types holds the data indiredtly

* Reference types holds default value

* Examples for reference types: Classes,objects,Arrays,Indexers,Interfaces

www.csetube.in

Page 6: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

6

6

16) Explain with example declaration of primitive data types in C#.

What is Data Type?

The type of data that a variable contains is called Data Type (type). A Data Type is a

classification of things that share similar type of qualities or characteristics or behavior.

C# is strongly typed language so every variable and object must have a type.

There are two types of data type in C#

1. primitive types (or) predefined

Ex: byte, short, int, float, double, long ,char, bool, DateTime, string, object etc..

2. non-primitive types (or) User Defined

Ex: class , struct , enum , interface, delegate, array.

In C#, based on what a variable contains there is two types of built-in data type

Value types

A variable holds actual values then that type of data types are value types. These value types are

stored in “stack” memory and these value types are fixed in size. If you assign a value of a

variable to another variable it will create two copies.

Ex: byte, short, int, float, double, long ,char, bool, DateTime.

Primitive data types are value types except string, object.

Object type is superior to all types. It can store any type or any size of data. It helps in

inheritance process.

Struct, enum are value types.

Reference types

A variable holds a reference to the value, then that type of data types are reference types. These

reference types are stored in “heap” memory and these types are not fixed in size. They are

maintained in system managed heap but it also uses stack to store reference of the heap. Two

primitive types (string and object) and non-primitive data types (class, interface & delegate) are

examples of reference type.

Ex: class, interface, delegate, string, object and array

17) Define a “Class” in C#.

A class is a user-defined data type with a template that serves to define it properties. Once a

class type has been defined, we can create variables of that type using declarations wich are

similar to basic type declarations. These variables are known as instances of classes, which are

actual objects.

www.csetube.in

Page 7: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

7

7

The syntax for class definition is :

Class className

{

[ variables declaration;]

[ methods declaration;]

}

18) Differntiate Passing by reference and Passing by value.

Passing by Reference vs. Passing by Value

By default, when a value type is passed to a method, a copy is passed instead of the object itself.

Therefore, changes to the argument have no effect on the original copy in the calling method.

You can pass a value-type by reference by using the ref keyword.

When an object of a reference type is passed to a method, a reference to the object is passed.

That is, the method receives not the object itself but an argument that indicates the location of the

object. If you change a member of the object by using this reference, the change is reflected in

the argument in the calling method, even if you pass the object by value.

19) Differentiate value and reference parameters with an example.

Passing Parameters

In C#, arguments can be passed to parameters either by value or by reference. Passing by reference

enables function members, methods, properties, indexers, operators, and constructors to change the

value of the parameters and have that change persist in the calling environment. To pass a parameter by

reference, use the ref or out keyword. For simplicity, only the ref keyword is used in the examples in this

topic.

The following example illustrates the difference between value and reference parameters.

class Program

{

static void Main(string[] args)

{

int arg;

// Passing by value.

// The value of arg in Main is not changed.

arg = 4;

squareVal(arg);

Console.WriteLine(arg);

// Output: 4

// Passing by reference.

// The value of arg in Main is changed.

arg = 4;

www.csetube.in

Page 8: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

8

8

squareRef(ref arg);

Console.WriteLine(arg);

// Output: 16

}

static void squareVal(int valParameter)

{

valParameter *= valParameter;

}

// Passing by reference

static void squareRef(ref int refParameter)

{

refParameter *= refParameter;

}

}

20) What is a signature of a method?

Method Signatures

Methods are declared in a class or struct by specifying the access level such as public or private, optional

modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters.

These parts together are the signature of the method.

21) Explain with examples the purpose of Constructor/Destructor

Constructors are special methods, used when instantiating a class. A constructor can never return

anything, which is why you don't have to define a return type for it. A normal method is defined

like this:

For example, we have a Car class, with a constructor which takes a string as argument. Of

course, a constructor can be overloaded as well, meaning we can have several constructors, with

the same name, but different parameters. Here is an example:

public Car()

{

}

public Car(string color)

{

this.color = color;

}

If you run this code, you will see that the constructor with no parameters is called first. This can be

used for instantiating various objects for the class in the default constructor, which can be called

from other constructors from the class. If the constructor you wish to call takes parameters, you

can do that as well.

Here is a simple example:

www.csetube.in

Page 9: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

9

9

public Car(string color) : this()

{

this.color = color;

Console.WriteLine("Constructor with color parameter called!");

}

public Car(string param1, string param2) : this(param1)

{

}

If you call the constructor which takes 2 parameters, the first parameter will be used to

invoke the constructor that takes 1 parameter.

Destructors

Since C# is garbage collected, meaning that the framework will free the objects that you no

longer use, there may be times where you need to do some manual cleanup. A destructor, a

method called once an object is disposed, can be used to cleanup resources used by the

object. Destructors doesn't look very much like other methods in C#. Here is an example of

a destructor for our Car class:

~Car()

{

Console.WriteLine("Out..");

}

Once the object is collected by the garbage collector, this method is called.

22) How will you create objects of a class?

Creating an object is referred to as instantiating an object. Objects in C# are created ujsing the new

operator.

EXAMPLE

Class Rectangle

{

Int length;

Int width;

Public void GetData(int x, int y)

{

Length = x;

Width = y;

}

}

Object creation steps :

(1) Declare class Rectangle as shown above.

(2) Create an object of type Rectangle :

Rectangle rect1; // declare the variable to hold reference

www.csetube.in

Page 10: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

10

10

(3) Rect1 = new Rectangle(); // instantiate ( Assigns the object reference to the variable)

Steps (2) and (3) can be combined into one as shown below :

Rectangle rect1 = new Rectangle();

Action

Statement Result

Declare

variable

rect1 of

type

Rectangle

Rectangle rect1;

rect1

Rect1 is the variable to hold

the object reference

Instantiate Rect1 = new

Rectangle( );

rect1 Rectangle object

Rect1 points to object

instance

23) How will you access the members of a created object?

Rectangle rect1;

= new Rectangle( );

Rectangle rect2 = new rectangle( );

The instance variables of the Rectangle class may be

accessed and assigned values as follows :

rect1.length = 15; rect1.width = 10;

rect2.length = 20; rect2.width = 12;

We can also call the GetData method to set values for variable length and width as follows ;

Rect1.GetData(15,10); // calling the method

24) What are constructos? Give an example.

It should be noted that the objects that are created must be initialized. One approach would

be to use dot operator to access instance variables and assign values. It is a tedious approach to

initialize instance variable.

It would be simpler and more concise to initialize an object when it is first created.

C# supports a special type of method, called a constructor, that enables an object to initialize itself

when it is created.

Example

Class Rectangle

{

Public int length;

Public int width;

Public Rectangle(int x,int y) // constructor method

{

Length = x;

Width = y;

}

}

Null

www.csetube.in

Page 11: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

11

11

Class test

{

Public static void Main()

{

Rectangle rect1 = new Rectangle(15,10); // calling constructor

….

}

25) Explain the usage of „this‟ reference.

this

The this keyword refers to the current instance of the class. Static member functions do not have

a this pointer. The this keyword can be used to access members from within constructors, instance

methods, and instance accessors.

The following are common uses of this:

To qualify members hidden by similar names:

example:

public Employee(string name, string alias)

{

this.name = name;

this.alias = alias;

}

26) What are access modifiers? Explain their purpose.

Access Modifiers

Access modifiers are keywords used to specify the declared accessibility of a member or a type.

public

protected

internal

private

public

The public keyword is an access modifier for types and type members. Public access is the most

permissive access level. There are no restrictions on accessing public members.

www.csetube.in

Page 12: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

12

12

private

The private keyword is a member access modifier. Private access is the least permissive access

level. Private members are accessible only within the body of the class or the struct in which they

are declared.

protected

The protected keyword is a member access modifier. A protected member is accessible from

within the class in which it is declared, and from within any class derived from the class that

declared this member.

A protected member of a base class is accessible in a derived class only if the access takes place

through the derived class type. For example, consider the following code segment:

internal

The internal keyword is an access modifier for types and type members. Internal members are

accessible only within files in the same assembly.

A common use of internal access is in component-based development because it enables a group

of components to cooperate in a private manner without being exposed to the rest of the

application code. For example, a framework for building graphical user interfaces could provide

Control and Form classes that cooperate using members with internal access. Since these

members are internal, they are not exposed to code that is using the framework.

27) Differentiate static and non-static members of a class.

C# Static Method

Static methods have no instances. They are called with the type name, not an instance identifier.

They are slightly faster than instance methods because of this. Static methods can be public or

private. They cannot use the this instance expression.

Static Modifier

Key point:Static methods are called without an instance reference.

Example

This program defines both static methods and regular instance methods and calls them both. The

static methods use the static keyword somewhere in the method declaration signature, usually as

the first keyword or the second keyword after public.

Static methods cannot access non-static class level members and do not have a 'this' pointer.

Instance methods can access those members, but must be called through an object instantiation,

which causes another step and level of indirection.

www.csetube.in

Page 13: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

13

13

28) What is enumeration?

Enumeration is a user-defined integer type which provide a way for attaching names to numbers.

29) Explain the syntax for declaring data type enumeration and give examples.

An enumeration (enum) is a value data type. It is a special integer data type. The declaration of this

data type defines a type name for a related group of symbolic constants. The associating integral data

type is known as underlying data type.

The syntax for defining enum is

Enum enumBase[:dataType]

{

Enumerator1,

Enumerator2,

….

enumeratorN

}

Where

Enum is a keyword indicating enumerator data type.

Enum Base is the name used to identify the specific enumeration.

Data type is one of the types from byte,sbyte,short,ushort,int,uint,long, or ulong.

Enumerator1,enumerator2,…enumeratorN are list of identifiers representing enum members.

EXAMPLE

enum Vehicle : byte

{

Car,bus,van,lorry

}

is an enumeration with underlying byte data type, and

enum Vehicle

{

Car,bus,van,lorry

}

is an enumeration with underlying int data type.

30) What is type conversion? Explain with examples.

A data type can be explicitly converted into a desired data type. This feature is known

as casting. It is accomplished by using the cast operator.

www.csetube.in

Page 14: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

14

14

The general format for type conversion :

(data type) expression

Example

(long) (10+25) converts the integer constant 35 to long.

(float) 1 converts the integer constant 1 to the float value 1.0

31) Differentiate class and structure

Category Structure (struct) class

Data Type Value type Reference type

Storage type Stack Heap

Inheritance Not supported Supported

Default values zero Null

Field iniialization Not permitted permitted

Construcor Not allowed Allowed

Destructors Not supported Supported

Assignment

operation

Copies the values Copies the reference

32) What is type conversion? Explain with examples.

A data type can be explicitly converted into a desired data type. This feature is known

as casting. It is accomplished by using the cast operator.

The general format for type conversion :

(data type) expression

Example

(long) (10+25) converts the integer constant 35 to long.

(float) 1 converts the integer constant 1 to the float value 1.0

33) Explain boxing and unboxing. Boxing

Conversion of value type to an object type is known as boxing. Boxing permits an implicit conversion of

value type to an object type. Boxing a value means allocating an object instance , and the value of the

value type is copied into that object instance.

Example

The following is the value type declaration :

Int x = 256;

The following statement implicitly applies the boxing operation on the variable x :

Object obj = x;

The value of variable x is stored on stack and it can be directly accessed. The boxing of x results in

allocating memory on stack for obj reference and memory for data on heap.

www.csetube.in

Page 15: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

15

15

Unboxing

Unboxing performs the opposite operationnof boxing. Conversion of object type to value type is known

as Unboxing.

Example

Object obj = 256;

Int x = (int)obj; // unboxing

34) Explain checked and unchecked operators.

Overflow checking for arithmetic operations and conversion of integer types are

controlled by checked and unchecked operators.

If an operation is checked, an overflow error will be thrown when an overflow occurs.

If it is not checked , the error is not reported and the overflowing bits are discarded.

Example

Int p = checked ( x * y ); // will check for the overflow if any, and an error is

reported(or an exception is thrown).

The code

Int p = unchecked ( x * y) ; // will result in loss of bits when an overflow occurs.

35) Explain with syntax and flowchart a) While loop construct b) Do while loop construct

c)for loop construct

While loop construct

While (boolExpr)

{

embedStmt;

}

Do While loop construct

Do

[

embedStmt;

}

While (boolExpr);

for loop construct

for (Expr_1; boolExpr; expr_2)

{

embedStmt;

}

36) What are exceptions and How exceptions are handled in C# programs?

During execution of a program, an unexpected situation or errors may occur and

they are called exceptions. When an exception occurs , the linear flow of control through the

program is altered. When an exception is thrown, the CLR searches for a method that

can handle the exception. An exception handler is used to catch the exception that is thrown. Exception handling is an in built mechanism in .NET framework to detect and handle run time

errors. Exceptions are defined as anomalies that occur during the execution of a program. The

.NET framework provides a rich set of standard exceptions that are used during exceptions

handling.

37) Give examples of predefined Exception classes in C#.

Sno Exception Type remarks

1 ArgumentException Invalid argument

2 ArithmeticException Arithmetic Overflow or Underflow

3 IndexOutOfRangeException An array index is out of range

4 StackOverflowException Stack overflow error

5 DivideByZeroException Error by dividing a value by zero

6 ArgumentNullException A null argument is passed to a method

resulting in an error

www.csetube.in

Page 16: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

16

16

38) Explain briefly the exception handling mechanism in C#.

Exception handling is an in built mechanism in .NET framework to detect and handle run time

errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that

occur during the execution of a program. They can be because of user, logic or system errors.

C# provides three keywords try, catch and finally to do exception handling. The try encloses the

statements that might throw an exception whereas catch handles an exception if one exists. The finally

can be used for doing any clean up process.

The general form try-catch-finally in C# is shown below

try

{

// Statement which can cause an exception.

}

catch(Type x)

{

// Statements for handling the exception

}

finally

{

//Any cleanup code

}

If any exception occurs inside the try block, the control transfers to the appropriate catch block and

later to the finally block.

39) Explain the syntax of a) the throw statement b) the try statement c) user defined exceptions

// try_catch_example.cs

using System;

class MainClass

{

static void ProcessString(string s)

{

if (s == null)

{

throw new ArgumentNullException();

}

}

static void Main()

{

try

{

string s = null;

ProcessString(s);

}

catch (Exception e)

{

www.csetube.in

Page 17: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

17

17

Console.WriteLine("{0} Exception caught.", e);

}

}

}

---------------------------------------------------------- // try_catch_finally.cs

using System;

public class EHClass

{

static void Main()

{

try

{

Console.WriteLine("Executing the try statement.");

throw new NullReferenceException();

}

catch (NullReferenceException e)

{

Console.WriteLine("{0} Caught exception #1.", e);

}

catch

{

Console.WriteLine("Caught exception #2.");

}

finally

{

Console.WriteLine("Executing finally block.");

}

}

}

Sample Output Executing the try statement.

System.NullReferenceException: Object reference not set to an instance of an object.

at EHClass.Main() Caught exception #1.

Executing finally block.

40) Write C# program to illustrate exception handling a) for stack over flow b) divide by zero

exception

Example-2 using System;

class Program

{

static void Main()

{

try

{

int value = 1 / int.Parse("0");

Console.WriteLine(value);

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

www.csetube.in

Page 18: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

18

18

}

}

}

The Program output

Attempt to divide by zero

41) Explain with an example how „DivideByZero‟ exception is handled in C#.

class ExceptionTest

{

static double SafeDivision(double x, double y)

{

if (y == 0)

throw new System.DivideByZeroException();

return x / y;

}

static void Main()

{

double a = 98, b = 0;

double result = 0;

try

{

result = SafeDivision(a, b);

Console.WriteLine("{0} divided by {1} = {2}", a, b, result);

}

catch (DivideByZeroException e)

{

Console.WriteLine("Attempted divide by zero.");

}

}

}

42) Define an array.

An array is a data structure that contains a number of subscripted variables. Each subscripted variable is

Known as an element of the array. All the elements are of the same data type.

An array is a reference data type in C#.

43) Explain array declaration and instantiation in C# with an example.

Syntax for array declaration

dataType[ ] arrayName; //declares a reference to an array

arrayName = new dataType[size]; // allocates memory

Example-1

Float[ ] x; // declaration of an array

X = new float[5]; // array has 5 elements

www.csetube.in

Page 19: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

19

19

The first statement creates an one-dimensional array x. In the second statement , memory allocated

Using the new operator.

Example-2

Char[ ] str;

Str = new char[20];

Example-3

Int k = 25;

Float[] f;

F = new float[k];

44) Explain declaration and instantiation of a two dimensional array in C#.

Syntax for 2D array declaration ;

dataType [ , ] arrayName; // declaration of a 2D array

arrayName = new dataType[size1,size2]; // size1, and size2 are the no of rows

and no of columns resp.

Example-1

Int[ , ] s = new int[3,2]; // Defines a two-dimensional integer array a.

Example-2

Char[ , ] s = new char[10,20]; // 2D array to hold 200 elements

45) Write short notes on a) creation of three dimensional arrays b)creation of jagged arrays

The syntax for creating Three-dimensional array

dataType[ , , ] arrayName;

arrayName = new dataType[size1,size2,size3];

Example

Char[ , , ] book; // Declares a 3-dimensional array book

Book = new char[20, 40, 80]; // creates 3D array book

46) Tabulate the difference between regular and jagged arrays.

S. No Regular array Jagged array

1 Array of elements of non-array type Array of elements of array type

2 Multi dimensional array subscripts are

separated by comma within an open

and closing square brackets

Each array subscripts is enclosed

within separate square brackets

3 Shapes are regular Shapes are irregular

4 Declaration contains only one pair of

square brackets

Declaration contains two or more

pairs of square brackets

47) Differentiate „const‟ and „readonly‟ in C#.

www.csetube.in

Page 20: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

20

20

const

A constant member is defined at compile time and cannot be changed at runtime. Constants are declared

as a field, using the const keyword and must be initialized as they are declared. For example;

public class MyClass

{

public const double PI = 3.14159;

}

PI cannot be changed in the application anywhere else in the code as this will cause a compiler error

readonly

A read only member is like a constant in that it represents an unchanging value. The difference is that a

readonly member can be initialized at runtime, in a constructor as well being able to be initialized as

they are declared. For example:

public class MyClass

{

public readonly double PI;

public MyClass()

{

PI = 3.14159;

}

}

48) What is ArrayList?

The main problem of traditional arrays is that their size is fixed by the number you specify when declaring

the array variable: you cannot add items beyond the specified dimension. Another limitation is that you

cannot insert an item inside the list.

To overcome this, you can create a linked list. Instead of working from scratch, the .NET Framework

provides the ArrayList class. With the ArrayList class, you can add new items to a list, insert items inside a

list, arrange items of a list, check the existence of an item in a list, remove an item from the list, inquire about

the list, or destroy the list. These operations are possible through various properties and methods.

The ArrayList class is defined in the System.Collections namespace.

EXAMPLE

using System.Collections;

class Program

{

static void Main()

www.csetube.in

Page 21: Cnf Unit-i - 2 Marks Csetube

www.csetu

be.in

21

21

{

//

// Create an ArrayList and add three elements.

//

ArrayList list = new ArrayList();

list.Add("One");

list.Add("Two");

list.Add("Three");

}

}

49) Differentiate an „array‟ and „arrayList‟ in C#.

C# : Difference between Array and Arraylist

System.Array System.Collections.ArrayList

1 Arrays are strongly typed.

That is all the elements have to be of the

same type. For example an array of integers

has to have all integers. It cannot have a

mix of integers and strings.

An arraylist is NOT strongly typed.

You can have a combination of built in types

(int,string etc) in your arraylist.

2 Cannot be dynamically resized.

(Note :Array.Resize() doesnot actually

resize the existing array. It infact creates a

new array with the required length and

copies values from the old array to new

array. Using the Resize is more memory

intensive than AddRange() in arraylist)

Can be dynamically resizedusing the method

Arraylist.AddRange()

3. Eg

int[] myIntArray = new int[2]

myIntArray[0]=10;

myIntArray[1]=20;

Eg

ArrayList leaderNames = new ArrayList();

leaderNames.Add("Obama");

leaderNames.Add(5);

www.csetube.in