cs2041 unit i question bank

Upload: abishek

Post on 09-Mar-2016

24 views

Category:

Documents


0 download

DESCRIPTION

question bank for c#anna university , unit 1

TRANSCRIPT

KCG College of Technology,Chennai 600097

61

Department of Computer Science and EngineeringCS2041 C# and .NET Framework

UNIT I Two Marks Questions & Answers1) 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 users 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.

SlnoInterfaceImplementation

1It is users view point. (What part)It is suppliers view point. (How part)

2It is used to interact with the outside worldIt describes how the delegated responsibility is carried out.

3User is permitted to access the interfaces onlyFunctions or methods are permitted to access the data.

4It encapsulates the knowledge about the object.It provides the restriction of access data by the user.

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?

.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. Quick Definition .NET is an initiative to integrate all Microsoft products with the Next Generation web. .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.

In brief .NET platform provides a new environment for creating and running robust,scalable and distributed applications over the web.

It consists of three distinct technologies

a)Common Language Runtime

Framework base classes

User and program Interfaces(ASP.NET and Winforms)

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# ProgramHello, world

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

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 :

boolfloatnamespacestatic

byteFornewstring

charforeachprivatethis

catchfinallyoverridethrow

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 :

a) They have alphabets,digits and underscore characters.

b) They must not begin with a digit.

14) Why do we require type conversion operation?

There is a need to convert a data of one type to another before it is used in arithmetic operations or to store a value of one type into a variable of another type .for example consider the code below : byte b1 = 50; byte b2 = 60; byte b3 = b1 + b2;

15) What do you mean by implicit conversion?

It can always be performed without any loss of data. For numeric types, this implies that the destination type can be fully representing the range of the sources type. For example, a short can be converted implicitly to an int, because the shott range is a subset of the int range. Therefore, Short b= 75; Int a=b; //implicit conversion. Are valid statement.

16) What do you mean by explicit conversion?

There are many conversions that cannot be implicitly made between types. If we attempt such conversions, the complier will give an error message.

17) 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.There are 3 types of Escape Sequences.They are

(a) Simple(b) Hexadecimal(c) Unicode character Escape Sequences

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

Literal constantMeaningLiteral constantMeaning

'\a'alert\xhhhGeneral format of hexadecimal ES

'\b'Back space\uhhhhGeneral format of Unicode character ES

'\f'Form feed

'\n'New line

'\r'Carriage return

'\t'Horizontal tab

'\v'Vertical tab

'\''Single quote

'\'''Double quote

'\\'Back slash

'\o'Null

18) 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,Interfaces19) 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 typeValue 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

20) 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.The syntax for class definition is :

Class className

{

[ variables declaration;]

[ methods declaration;]

}

21) 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 areference typeis 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.

22) 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 thereforoutkeyword. For simplicity, only therefkeyword 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;

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;

}

}

23) What is a signature of a method?

Method Signatures

Methods are declared in aclassorstructby specifying the access level such aspublicorprivate, optional modifiers such asabstractorsealed, the return value, the name of the method, and any method parameters. These parts together are thesignatureof the method.

24) 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:

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.25) 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 (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 RectangleRectangle rect1;

rect1Rect1 is the variable to hold the object reference

InstantiateRect1 = new Rectangle( );

rect1 Rectangle objectRect1 points to object instance

26) 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

27) 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. ExampleClass Rectangle{

Public int length;Public int width;

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

{

Length = x;

Width = y;

}

}

Class test

{

Public static void Main()

{

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

.

}

28) Explain the usage of this reference.

this

Thethiskeyword refers to the current instance of the class. Static member functions do not have athispointer. Thethiskeyword can be used to access members from within constructors, instance methods, and instance accessors.

The following are common uses ofthis:

To qualify members hidden by similar names:

example:

public Employee(string name, string alias)

{

this.name = name;

this.alias = alias;

}

29) 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.

publicprotectedinternalprivatepublic

Thepublickeyword 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.

private

Theprivatekeyword 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

Theprotectedkeyword 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

Theinternalkeyword 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.

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

C# Static Method

Static methodshave 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 ModifierKey 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 methodscannot 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.

31) What is enumeration?

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

32) 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 Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

// Inside some method

Days day1, day2;

int day3;

day1 = Days.Sat;

day2 = Days.Tue;

day3 = (int) Days.Fri;

Console.WriteLine(day1);

Console.WriteLine(day2);

Console.WriteLine(day3);

Output : Sat Tue

6 33) Differentiate class and structure

CategoryStructure (struct)class

Data TypeValue typeReference type

Storage typeStackHeap

Inheritance Not supportedSupported

Default values zeroNull

Field initializationNot permittedpermitted

ConstrucorNot allowedAllowed

DestructorsNot supportedSupported

Assignment operationCopies the valuesCopies the reference

34) 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

35) 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.

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

36) 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.

37) 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;

}

38) 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. 39) Give examples of predefined Exception classes in C#.

SnoException Typeremarks

1ArgumentExceptionInvalid argument

2ArithmeticExceptionArithmetic Overflow or Underflow

3IndexOutOfRangeExceptionAn array index is out of range

4StackOverflowExceptionStack overflow error

5DivideByZeroExceptionError by dividing a value by zero

6ArgumentNullExceptionA null argument is passed to a method resulting in an error

40) 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.41) 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)

{

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.

42) 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);

}

}

}

The Program output

Attempt to divide by zero

43) Explain with an example how DivideByZero exception is handled in C#.

class ExceptionTest

{

staticdouble SafeDivision(double x, double y)

{

if (y == 0)

thrownew System.DivideByZeroException();

return x / y;

}

staticvoid 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.");

}

}

}

44) 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#.45) 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

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];

46) 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

47) 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

48) Tabulate the difference between regular and jagged arrays.

S. NoRegular arrayJagged array

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

2Multi dimensional array subscripts are separated by comma within an open and closing square bracketsEach array subscripts is enclosed within separate square brackets

3Shapes are regularShapes are irregular

4Declaration contains only one pair of square bracketsDeclaration contains two or more pairs of square brackets

49) Differentiate const and readonly in C#.

constA constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using theconstkeyword and must be initialized as they are declared. For example;

public class MyClass

{

public const double PI = 3.14159;

}

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

readonlyA read only member is like a constant in that it represents an unchanging value. The difference is that a readonlymember 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;

}

}

50) What is ArrayList?

The main problem of traditionalarraysis 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 theArrayListclass. With theArrayListclass, 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.

TheArrayListclass is defined in theSystem.Collectionsnamespace. EXAMPLEusing System.Collections;

class Program

{

static void Main()

{

//

// Create an ArrayList and add three elements.

//

ArrayList list = new ArrayList();

list.Add("One");

list.Add("Two");

list.Add("Three");

}

}

51) Differentiate an array and arrayList in C#.

C# : Difference between Array and Arraylist

System.ArraySystem.Collections.ArrayList

1Arrays 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.

2Cannot 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 =newint[2]myIntArray[0]=10;

myIntArray[1]=20;

Eg

ArrayListl =newArrayList();l.Add("Obama");l.Add(5);

16 Marks with Answers

1.Explain in detail about the activities of CLR.Common Language Runtime is the backbone of the .NET framework. CLR takes care of a number of low-level executions such as application hosting, thread handling, memory management, security checks and application performance. Its primary role is to locate, load, and manage the .NET types (class, array, object etc.). The term service refers to as a collection of services that are required to execute a code. The beauty of CLR is that all .NET-supported languages can be executed under this single defined runtime layer. The spinal cord of CLR is represented by a library refers to as mscoree.dll (common object runtime execution engine). When an assembly is referenced for use, mscoree.dll is automatically loaded.

The CLR first locates the referenced assembly, and then it loads it into memory, compiles the associated IL code into platform specific instructions, performs security related checks, and finally executes the code.

In Depth, the .NET compilation process completes in two stages; first, the C# code you write is compiled into an Intermediate Code (MSIL). All .NET languages are compiled into virtual identical IL code. The compiled file with IL code is referred to as Assembly.

Managed Code

The second level of compilation happens just before the application is executed. At this point, the IL code is compiled into low-level native machine code. This stage is known-as Just-In-Time (JIT) Compilation. Finally .NET CLR produces the executable or library files and executes the code.

Managed CodeCode developed and running under the control of the CLR is often termed managed code Microsoft shared the idea of IL code from Java byte code in which IL code can be quickly translated into native machine code. In other words, by compiling to IL code, you obtain platform independence for .NET in much same way as compiling java code.

IL code is compiled (JIT compilation), whereas java byte code was interpreted. One of the advantages of java was that, on execution, the process of translating from java byte code to native executable resulted in loss of performance. Instead of compiling the entire applications in one go; the JIT compiler simply compiles each portion of code. This is why we can expect that execution of managed IL code will be as fast as executing native code.

IL is the backbone for every managed application. In a sense, the language is only recognized by .NET framework is IL.

2. Explain about various Namespaces of .NET framework.The .NET Framework class library includes classes that support the following functions:

base and user-defined data types;

support for handling exceptions;

input/output and stream operations;

communications with the underlying system;

access to data;

ability to create Windowsbased GUI applications;

ability to create webclient and server applications;

support for creating web services.

All classes implemented in the .NET class library are organized into namespaces. Each namespace contains classes and other types that are related to the specific task or set of tasks input/output operations, web applications creation, working with data and XML, and so on. Table 3.1 shows the most important namespaces in the .NET class library.

Table 3.1. The main namespaces in the .NET class library

NamespaceDescription

SystemContains fundamental classes and base classes that define common value and reference data types, events and event handlers, interfaces, processing exceptions, data conversion, mathematics, as well as garbage collection and application environment management. Some of the classes defined in the namespace are covered in this chapter and also in Chapters 4 and 5.

System.IOProvides classes that support asynchronous and synchronous reading from and writing to data streams and files. Contains classes like FileStream, MemoryStream, Path, and Directory. We will learn about this namespace and its classes in the next chapter.

System.CollectionsContains interfaces and classes that define various collections of objects, such as lists, arrays, hash tables, stacks, queues, and dictionaries. The classes defined in this namespace are covered in this chapter.

System.ThreadingProvides classes and interfaces that support multithreaded programming. Contains classes such as Thread, ThreadPool, Mutex, and AutoResetEvent.

System.ReflectionContains classes that provide dynamic binding and a managed view of loaded types, methods, and fields. Contains classes such as Assembly, Module, and MethodInfo.

System.SecurityImplements a security system, including base classes for permissions. Includes classes of the likes of SecurityManager, PermissionSet, and CodeAccessPermission.

System.NetProvides support for network programming. Includes, for example, the classes HttpWebRequest, IPAddress, Dns, and Connection. We will learn about this namespace and its classes in the next chapter.

System.DataContains classes that implement ADO.NET. Child namespaces include OLEDB, and SqlClient. This namespace will be discussed in Chapter 12.

System.XMLThe System.XML namespace provides support for processing XML documents. Child namespaces include Schema, XSL, and XPath. We will discuss this namespace and its secondary namespaces in Chapter 14.

System.WebServes as a base for ASP.NET applications. Contains such classes as HTTPRequest, HTTPResponse, and HTTPServerUtility. Child namespaces include Caching, Configuration, Security, and UI. We will discuss this namespace and its secondary namespaces in Chapters 6 and 7.

System.Web.ServicesEnables us to build and use web services. Secondary namespaces include Description, Discovery, and Protocols. We will discuss this namespace and its secondary namespaces in Chapter 15.

System.Windows.FormsContains classes used to create form-based Windows applications. We will discuss this namespace in Chapters 8, 9, and 10

System.DrawingProvides access to the graphics functionality of GDI+. Contains secondary namespaces such as Design, Drawing2D, Imaging, Printing, and Text. We will discuss this namespace and its secondary namespaces in Chapter 11.

System.Globalization System.ResourcesContains classes that define culture-related information language, country/region, calendar, and so on. Classes from the Resources namespace are used to create localized Windows and web applications.

After this brief overview of most of the chapters in the book, we are ready to start our journey through the .NET Framework class library. Main namespaces are shown in Figure 3.1. Our first stop is a little bit unusual instead of covering the Object class that is, the ultimate ancestor for all of the classes in the .NET Framework class library we will discuss the Console class. The following section will explain why we do this.

Figure 3.1. Main namespaces in the .NET framework class library3.1 Console class and applications Using the System.Console class, we can implement the simplest .NET application a console application that runs in a system-supplied window and does not require a graphical user interface. Since in this and several other chapters of this book we will use the console applications heavily, we will start this chapter with an overview of the Console class.

The Console class represents the standard input, output, and error streams. Applications built on this class can read characters from the standard input stream and write characters to the standard output stream. Errors are written to the standard error output stream. These three streams are automatically associated with the console on which the application starts and we can obtain them via the In, Out, and Error properties of the Console class. By default, the standard input stream is a System.IO. TextReader object, the output and output error streams are System.IO.TextWriter objects. If we need it, we can associate input and output streams with different streams file streams, network streams, memory streams, and so on.

In Visual Basic.NET, we create a console application by creating a new module that contains one subroutine called Main this is the entry point into our console application (see Figure 3.2):

Figure 3.2. Console application in action'---------------------------------------

' .NET Console Application

'---------------------------------------

Imports System

Module Cons

Sub Main()

Console.WriteLine(".NET Console application")

Console.ReadLine()

End Sub

End Module

The Read and ReadLine methods allow us to read a character or new line character from the standard input, while Write and WriteLine perform the output.

The SetIn, SetOut, and SetError methods allows us to specify different input, output, and error output streams. These methods take a parameter of TextWriter type that specifies the output stream.

3. Briefly explain all the control structures in C#.Control statements give you additional means to control the processing within the applications you develop. This section explores the syntax and function of the if, switch, do-while, for, foreach, goto, break, continue, and return statements.

If-then-else

The if statement has three forms: single selection, if-then-else selection, and multicase selection. Listing 5.23 contains an example of each form.

Listing 5.23: If-Else-ElseIf Example 1

//single selectionif (i > 0) Console.WriteLine("The number {0} is positive", i);//if-then-else selection

if (i > 0) Console.WriteLine("The number {0} is positive", i);else Console.WriteLine("The number {0} is not positive", i);

//multicase selectionif (i == 0) Console.WriteLine("The number is zero");else if (i > 0) Console.WriteLine("The number {0} is positive", i);else Console.WriteLine("The number {0} is negative", i);

The variable i is the object of evaluation here. The expression in an if statement must resolve to a boolean value type.

// Compiler Errorif (1) Console.WriteLine("The if statement executed");Console.ReadLine();

When the C# compiler compiles the preceding code, it generates the error "Constant value 1 cannot be converted to bool."

Listing 5.24 shows how conditional or (||) and conditional and (&&) operators are used in the same manner.

Listing 5.24: If-Then-Else Example 2

//Leap yearint year = 1974;if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) Console.WriteLine("The year {0} is leap year ", year);else Console.WriteLine("The year {0} is not leap year ", year);

Switch

From the example in Listing 5.25, you can see that the switch statement is similar to an if-else ifelse if-else form of an if statement.

Listing 5.25: Switch Example 1

string day = "Monday";Console.WriteLine("enter the day :");day = Console.ReadLine();

switch (day){ case "Mon": break; case "Monday": Console.WriteLine("day is Monday: go to work"); break; default: Console.WriteLine("default"); break;}

switch (strVal1){ case "reason1": goto case "reason2"; // this is a jump to mimic fall-through case "reason2": intOption = 2; break; case "reason 3": intOption = 3; break; case "reason 4": intOption = 4; break; case "reason 5": intOption = 5; break; default:intOption = 9; break;}

Do-While

The while loop allows the user to repeat a section of code until a guard condition is met. Listing 5.27 presents a simple while loop designed to find out the number of digits in a given value.

Listing 5.27: While Example

//find out the number of digits in a given numberint i = 123;int count = 0;int n = i;

//while loop may execute zero timeswhile (i > 0){ ++count; i = i / 10;}Console.WriteLine("Number {0} contains {1} digits.", n, count);

For a given number i = 123, the loop will execute three times. Hence the value of the count is three at the end of the while loop.

This example has one logical flaw. If the value of i is 0, the output of the code will be "Number 0 contains 0 digits." Actually, the number 0 contains one digit. Because the condition of the while loop i > 0 is false from the beginning for the value i = 0, the while loop does not even execute one time and the count will be zero. Listing 5.28 presents a solution.

Listing 5.28: Do Example

//find out the number of digits in a given numberint i = 0;int count = 0;int n = i;do{ ++count; i = i / 10;} while (i > 0);Console.WriteLine("Number {0} contains {1} digits.", n, count);

The do-while construct checks the condition at the end of the loop. Therefore, the do-while loop executes at least once even though the condition to be checked is false from the beginning.

For

The for loop is useful when you know how many times the loop needs to execute. An example of a for statement is presented in Listing 5.29.

Listing 5.29: For Example 1

for (int i = 0; i < 3; i++) a(i) = "test"

for (string strServer = Console.ReadLine();strServer != "q" && strServer != "quit";strServer = Console.ReadLine()){ Console.WriteLine(strServer);}

Listing 5.30 shows the use of a for loop with the added functionality of break and continue statements.

//For loop with break and continue statementsfor (int i = 0; i < 20; ++i){ if (i == 10)break; if (i == 5) continue; Console.WriteLine(i);}

The output of the code in the listing is as follows:

01 2 3 4 6 7 8 9

When i become 5, the loop skips over the remaining statements in the loop and goes back to the post loop action. Thus, 5 is omitted from the output. When i become 10, the program will break out of the loop.

ForEach

The foreach statement allows the iteration of processing over the elements in arrays and collections. Listing 5.31 contains a simple example.

Listing 5.31: ForEach Example 1

//foreach loopstring[] a = { "Chirag", "Bhargav", "Tejas" };foreach (string b in a)Console.WriteLine(b);

Within the foreach loop parentheses, the expression consists of two parts separated by the keyword in. To the right of in is the collection, and to the left is the variable with the type identifier matching whatever type the collection returns.

Listing 5.32 presents a slightly more complex version of the foreach loop.

Listing 5.32: ForEach Example 2

Int16[] intNumbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };foreach (Int16 i in intNumbers){ System.Console.WriteLine(i);}

Each iteration queries the collection for a new value for i. As long as the collection intNumbers returns a value, the value is put into the variable i and the loop will continue. When the collection is fully traversed, the loop will terminate.

GoTo

You can use the goto statement to jump to a specific segment of code, as shown in Listing 5.33. You can also use goto for jumping to switch cases and default labels inside switch blocks. You should avoid the overuse of goto because code becomes difficult to read and maintain if you have many goto jumps within your code.

Listing 5.33: GoTo Example

label1: ; //... if (x == 0) goto label1; //...

Break

The break statement, used within for, while, and do-while blocks, causes processing to exit the innermost loop immediately. When a break statement is used, the code jumps to the next line following the loop block, as you'll see in Listing 5.34.

Listing 5.34: Break Example

while (true){ //... if (x == 0) break; //...}Console.WriteLine("break");

Continue

The continue statement (shown in Listing 5.35) is used to jump to the end of the loop immediately and process the next iteration of the loop.

Listing 5.35: Continue Example

int x = 0;while (true){ //... if (x == 0) { x = 5; continue; } //...

if (x == 5) Console.WriteLine("continue"); //...}

Return

The return statement is used to prematurely return from a method. The return statement can return empty or with a value on the stack, depending upon the return value definition in the method (Listing 5.36 shows both). Void methods do not require a return value. For other functions, you need to return an appropriate value of the type you declared in the method signature.

Listing 5.36: Return Example void MyFunc1(){// ...if(x == 1)return;// ...}

int MyFunc2(){// ...if(x == 2)return 1919;// ...}

4. Explain in detail about various operators available in C#.An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C# has rich set of built-in operators and provides the following type of operators:

Arithmetic Operators

Relational Operators

Logical Operators

Bitwise Operators

Assignment Operators

Misc Operators

This tutorial explains the arithmetic, relational, logical, bitwise, assignment, and other operators one by one.

Arithmetic Operators

Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10 and variable B holds 20 then:

Show ExamplesOperatorDescriptionExample

+Adds two operandsA + B = 30

-Subtracts second operand from the firstA - B = -10

*Multiplies both operandsA * B = 200

/Divides numerator by de-numeratorB / A = 2

%Modulus Operator and remainder of after an integer divisionB % A = 0

++Increment operator increases integer value by oneA++ = 11

--Decrement operator decreases integer value by oneA-- = 9

Relational Operators

Following table shows all the relational operators supported by C#. Assume variable A holds 10 and variable B holds 20, then:

Show ExamplesOperatorDescriptionExample

==Checks if the values of two operands are equal or not, if yes then condition becomes true.(A == B) is not true.

!=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true.

>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.

=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.