CS2041 UNIT I Question Bank

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 61

1

Department of Computer Science and Engineering


CS2041 C# and .NET Framework
UNIT I
Two Marks Questions & Answers
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 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.
Slno
1
2
3
4

Interface
It is users view point. (What
part)
It is used to interact with the
outside world
User is permitted to access the
interfaces only
It
encapsulates the knowledge
about the object.

Implementation
It is suppliers view point.
(How part)
It describes how the delegated
responsibility is carried out.
Functions or methods are
permitted to access the data.
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?
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
2

3
a)Common Language Runtime
o Framework base classes
o 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# Program
Hello, world
The canonical Hello, world program can be written in C# as follows:
using System;
class Hello
{
static void Main()
{
3

4
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 :
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;
4

5
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
Meaning
Literal constant Meaning
constant
'\a'

alert

\xhhh

General format of
hexadecimal ES

'\b'

Back space

\uhhhh

General 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:
5

6
* 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

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

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

8
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 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.
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;
8

9
}
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 :
9

10
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

Declare
variable
rect1 of
type
Rectangle
Instantiate

Rectangle rect1;

Result
Rect1 is the variable to hold
the object reference

Null
rect1
Rect1 = new
Rectangle( );

Rect1 points to object


instance
rect1

Rectangle object

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.
Example
Class Rectangle
{
Public int length;
Public int width;
Public Rectangle(int x,int y) // constructor method
{
Length = x;
Width = y;
}
}
10

11
Class test
{
Public static void Main()
{
Rectangle rect1 = new Rectangle(15,10); // calling constructor
.
}
28) 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;
}
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.
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.

11

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

12

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

13

14

33) 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
Not permitted
permitted
initialization
Construcor
Not allowed
Allowed
Destructors
Not supported
Supported
Assignment
Copies the values
Copies the reference
operation
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.
14

15
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 Do While loop construct for loop construct
While (boolExpr)
Do
for (Expr_1; boolExpr; expr_2)
{
[
{
embedStmt;
embedStmt;
embedStmt;
}
}
}
While (boolExpr);
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#.
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
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.
15

16
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
{
16

17
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);
}
}
17

18
}
The Program output
Attempt to divide by zero
43) 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.");
}
}
}
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.
18

19
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. No
1
2
3
4

Regular array
Array of elements of non-array type
Multi dimensional array subscripts are
separated by comma within an open
and closing square brackets
Shapes are regular
Declaration contains only one pair of
square brackets

Jagged array
Array of elements of array type
Each array subscripts is enclosed
within separate square brackets
Shapes are irregular
Declaration contains two or more
pairs of square brackets

49) Differentiate const and readonly in C#.


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;

19

20

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;
}
}
50) 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()
{
//
20

21
// 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.Array
System.Collections.ArrayList
1 Arrays are strongly typed.
An arraylist is NOT strongly typed.
That is all the elements have to be of the You can have a combination of built in types
same type. For example an array of
(int,string etc) in your arraylist.
integers has to have all integers. It cannot
have a mix of integers and strings.
2 Cannot be dynamically resized.
Can be dynamically resizedusing the method
Arraylist.AddRange()
(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)
3. Eg
Eg
int[] myIntArray = new int[2]
ArrayList l = new ArrayList();
myIntArray[0]=10;
myIntArray[1]=20;
l.Add("Obama");
l.Add(5);

21

22

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.

22

23

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 Code
Code 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.
23

24
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
Namespace
System

Description
Contains 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.
24

25

Namespace

Description

System.IO

Provides 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.Collections

Contains 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.Threading

Provides classes and interfaces that support multithreaded programming. Contains


classes such as Thread, ThreadPool, Mutex, and AutoResetEvent.

System.Reflection

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

System.Security

Implements a security system, including base classes for permissions. Includes


classes of the likes of SecurityManager, PermissionSet, and
CodeAccessPermission.

System.Net

Provides 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.Data

Contains classes that implement ADO.NET. Child namespaces include OLEDB,


and SqlClient. This namespace will be discussed in Chapter 12.

System.XML

The 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.Web

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

25

26

Namespace

Description

System.Web.Services

Enables 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.Forms

Contains classes used to create form-based Windows applications. We will discuss


this namespace in Chapters 8, 9, and 10

System.Drawing

Provides 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.Resources

Contains 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 library

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

26

27
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 selection
if (i > 0)
Console.WriteLine("The number {0} is positive", i);
//if-then-else selection
27

28
if (i > 0)
Console.WriteLine("The number {0} is positive", i);
else
Console.WriteLine("The number {0} is not positive", i);
//multicase selection
if (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 Error
if (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 year
int 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)
{
28

29
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 number
int i = 123;
int count = 0;
int n = i;
//while loop may execute zero times
while (i > 0)
{
++count;
i = i / 10;
}
29

30
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 number
int 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 statements
for (int i = 0; i < 20; ++i)
{
if (i == 10)
30

31
break;
if (i == 5)
continue;
Console.WriteLine(i);
}
The output of the code in the listing is as follows:
0
1
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 loop
string[] 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
31

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

33
}
//...
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

33

34

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 Examples
Operator Description

Example

Adds two operands

A + B = 30

Subtracts second operand from the first

A - B = -10

Multiplies both operands

A * B = 200

Divides numerator by de-numerator

B / A= 2

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

++

Increment operator increases integer value by one

A++ = 11

--

Decrement operator decreases integer value by one

A-- = 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 Examples
Operator Description

Example

==

Checks if the values of two operands are equal or not, if yes


(A == B) is not true.
then condition becomes 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.

34

35
>

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 less than the value of


right operand, if yes then condition becomes true.

(A < B) is true.

>=

Checks if the value of left operand is greater than or equal to


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

<=

Checks if the value of left operand is less than or equal to the


(A <= B) is true.
value of right operand, if yes then condition becomes true.

Logical Operators
Following table shows all the logical operators supported by C#. Assume variable A holds Boolean value true and
variable B holds Boolean value false, then:
Show Examples
Operator Description

Example

&&

Called Logical AND operator. If both the operands are non


zero then condition becomes true.

(A && B) is false.

||

Called Logical OR Operator. If any of the two operands is


non zero then condition becomes true.

(A || B) is true.

Called Logical NOT Operator. Use to reverses the logical


state of its operand. If a condition is true then Logical NOT
operator will make false.

!(A && B) is true.

Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as follows:
p

p&q

p|q

p^q

1
35

36
1

Assume if A = 60; and B = 13; then in the binary format they are as follows:
A = 0011 1100
B = 0000 1101
----------------A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C# are listed in the following table. Assume variable A holds 60 and variable B
holds 13, then:
Show Examples
Operator Description

Example

&

Binary AND Operator copies a bit to the result if it exists in


(A & B) = 12, which is 0000 1100
both operands.

Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, which is 0011 1101

Binary XOR Operator copies the bit if it is set in one operand


(A ^ B) = 49, which is 0011 0001
but not both.

Binary Ones Complement Operator is unary and has the


effect of 'flipping' bits.

<<

Binary Left Shift Operator. The left operands value is moved


A << 2 = 240, which is 1111 0000
left by the number of bits specified by the right operand.

(~A ) = 61, which is 1100 0011 in 2's


complement due to a signed binary
number.

36

37

>>

Binary Right Shift Operator. The left operands value is


moved right by the number of bits specified by the right
operand.

A >> 2 = 15, which is 0000 1111

Assignment Operators
There are following assignment operators supported by C#:
Show Examples
Operator Description

Example

Simple assignment operator, Assigns values from right side


operands to left side operand

C = A + B assigns value of A + B into


C

+=

Add AND assignment operator, It adds right operand to the


left operand and assign the result to left operand

C += A is equivalent to C = C + A

-=

Subtract AND assignment operator, It subtracts right operand


C -= A is equivalent to C = C - A
from the left operand and assign the result to left operand

*=

Multiply AND assignment operator, It multiplies right


operand with the left operand and assign the result to left
operand

C *= A is equivalent to C = C * A

/=

Divide AND assignment operator, It divides left operand


with the right operand and assign the result to left operand

C /= A is equivalent to C = C / A

%=

Modulus AND assignment operator, It takes modulus using


two operands and assign the result to left operand

C %= A is equivalent to C = C % A

<<=

Left shift AND assignment operator

C <<= 2 is same as C = C << 2

>>=

Right shift AND assignment operator

C >>= 2 is same as C = C >> 2

&=

Bitwise AND assignment operator

C &= 2 is same as C = C & 2

^=

bitwise exclusive OR and assignment operator

C ^= 2 is same as C = C ^ 2

|=

bitwise inclusive OR and assignment operator

C |= 2 is same as C = C | 2
37

38
Miscillaneous Operators
There are few other important operators including sizeof, typeof and ? : supported by C#.
Show Examples
Operator Description

Example

sizeof()

Returns the size of a data type.

sizeof(int), returns 4.

typeof()

Returns the type of a class.

typeof(StreamReader);

&

Returns the address of an variable.

&a; returns actual address of the


variable.

Pointer to a variable.

*a; creates pointer named 'a' to a


variable.

?:

Conditional Expression

If Condition is true ? Then value X :


Otherwise value Y

is

Determines whether an object is of a certain type.

If( Ford is Car) // checks if Ford is an


object of the Car class.

as

Cast without raising an exception if the cast fails.

Object obj = new


StringReader("Hello");
StringReader r = obj as StringReader;

Operator Precedence in C#
Operator precedence determines the grouping of terms in an expression. This affects evaluation of an expression.
Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence
than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so the first
evaluation takes place for 3*2 and then 7 is added into it.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom.
Within an expression, higher precedence operators are evaluated first.
Show Examples
38

39
Category

Operator

Associativity

Postfix

() [] -> . ++ - -

Left to right

Unary

+ - ! ~ ++ - - (type)* & sizeof

Right to left

Multiplicative

*/%

Left to right

Additive

+-

Left to right

Shift

<< >>

Left to right

Relational

< <= > >=

Left to right

Equality

== !=

Left to right

Bitwise AND

&

Left to right

Bitwise XOR

Left to right

Bitwise OR

Left to right

Logical AND

&&

Left to right

Logical OR

||

Left to right

Conditional

?:

Right to left

Assignment

= += -= *= /= %=>>= <<= &= ^= |=

Right to left

Comma

Left to right

5. Explain about various string handling methods.

In C# programming, string is another kind of data type that represents Unicode Characters. It is
the alias of System.String however, you can also write System.String instead of string. It is the
sequence of character in which each character is a Unicode character.
39

40
There is no difference between string and String because string is the alias of System.String.
Most of the developers get confused what to use between sting and String. Technically there is
no difference between them and they can use any of them. However, you will have to use using
System to use the String in C#. Another difference is String is a class name whereas string is a
reserved keyword. You should always use string instead of String.

String Functions

Definitions

Clone()

Make clone of string.

CompareTo()

Compare two strings and returns integer value as


output. It returns 0 for true and 1 for false.

Contains()

The C# Contains method checks whether


specified character or string is exists or not in the
string value.

EndsWith()

This EndsWith Method checks whether specified


character is the last character of string or not.

Equals()

The Equals Method in C# compares two string


and returns Boolean value as output.

GetHashCode()

This method returns HashValue of specified


string.

GetType()

It returns the System.Type of current instance.

GetTypeCode()

It returns the Stystem.TypeCode for class


System.String.

IndexOf()

Returns the index position of first occurrence of


specified character.

ToLower()

Converts String into lower case based on rules of


the current culture.

ToUpper()

Converts String into Upper case based on rules of


the current culture.

Insert()

Insert the string or character in the string at the


specified position.

IsNormalized()

This method checks whether this string is in


Unicode normalization form C.

LastIndexOf()

Returns the index position of last occurrence of


specified character.

Length

It is a string property that returns length of


string.

Remove()

This method deletes all the characters from


beginning to specified index position.

Replace()

This method replaces the character.


40

41
Split()

This method splits the string based on specified


value.

StartsWith()

It checks whether the first character of string is


same as specified character.

Substring()

This method returns substring.

ToCharArray()

Converts string into char array.

Trim()

It removes extra whitespaces from beginning and


ending of string.

Programming Examples of C# String Function:


UsingSystem.Text;
namespacestring_function
{
classProgram
{
staticvoidMain(string[] args)
{
string firstname;
string lastname;
firstname = "Steven Clark";
lastname = "Clark";
Console.WriteLine(firstname.Clone());
// Make String Clone
Console.WriteLine(firstname.CompareTo(lastname));
//Compare two string value and returns 0 for true and
1 for false
Console.WriteLine(firstname.Contains( "ven")); //Check whether specified value exists or not in
string
Console.WriteLine(firstname.EndsWith( "n")); //Check whether specified value is the last
character of string
Console.WriteLine(firstname.Equals(lastname));
//Compare two string and returns true and false
Console.WriteLine(firstname.GetHashCode());
//Returns HashCode of String
Console.WriteLine(firstname.GetType());
//Returns type of string
Console.WriteLine(firstname.GetTypeCode());
//Returns type of string
Console.WriteLine(firstname.IndexOf( "e")); //Returns the first index position of specified value
the first index position of specified value
41

42
Console.WriteLine(firstname.ToLower());
//Covert string into lower case
Console.WriteLine(firstname.ToUpper());
//Convert string into Upper case
Console.WriteLine(firstname.Insert(0, "Hello")); //Insert substring into string
Console.WriteLine(firstname.IsNormalized());
//Check Whether string is in Unicode normalization
from C
Console.WriteLine(firstname.LastIndexOf( "e")); //Returns the last index position of specified
value
Console.WriteLine(firstname.Length);
//Returns the Length of String
Console.WriteLine(firstname.Remove(5));
//Deletes all the characters from begining to specified index.
Console.WriteLine(firstname.Replace( 'e','i')); // Replace the character
string[] split = firstname.Split( new char[] { 'e' }); //Split the string based on specified value
Console.WriteLine(split[0]);
Console.WriteLine(split[1]);
Console.WriteLine(split[2]);
Console.WriteLine(firstname.StartsWith( "S")); //Check wheter first character of string is same
as specified value
Console.WriteLine(firstname.Substring(2,5));
//Returns substring
Console.WriteLine(firstname.ToCharArray());
//Converts an string into char array.
Console.WriteLine(firstname.Trim());
//It removes starting and ending white spaces from
string.
}
}
}

Output

Steven Clark
1
True
False
False
42

43
1470518261
System.String
String
2
steven clark
STEVEN CLARK
HelloSteven Clark
True
4
12
Steve
Stivin Clark
St
v
n Clark
True
even
Steven Clark
Steven Clark

6. Explain about Enumerators and structures in C#.


Enumerators
Enumeration provides efficient way to assign multiple constant integral values to a single
variable. Enumeration improves code clarity and makes program easier to maintain. Enumeration
in C# also provides more security by better error-checking technology and compiler warnings.
An enumeration can be defined using enum keyword. In enumeration, you can define special set
of value that can be assigned with enumeration. For Example, you are creating an attendance log
application in which a variable can contains value only Monday to Friday. The other value will
not be applicable with variables. In order to fulfill this requirement you need to use enumeration
that will hold only assigned values and will returns numeric position of values starting with zero.
using System;
namespace Enumeration
{
// creating enumeration for storing day.
public enum attandance
43

44
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday
}
class Program
{
static void Main(string[] args)
{
attandance present = attandance.Monday;//Valid
Console.WriteLine(present);
//attandance absent = attandance.Sunday;//Invalid
Console.ReadLine();
}
}
}

Output

Monday
In the preceding example, we create attendance enumeration in which 5 values are assigned as
Monday, Tuesday, Wednesday, Thursday and Friday. Only these 5 values are valid entry for
attendance enumeration variable. If you assign other entry as Sunday or Saturday, it will be
invalid and you will get compile time error in C# programming.
Structures
44

45

In C#, a structure is a value type data type. It helps you to make a single variable hold related data of various data types.
The struct keyword is used for creating a structure.
Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to
track the following attributes about each book:

Title

Author
Subject
Book ID

Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than
one member for your program.
For example, here is the way you can declare the Book structure:
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
The following program shows the use of the structure:
using System;
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
45

46

public class testStructure


{
public static void Main(string[] args)
{
Books Book1; /* Declare Book1 of type Book */
Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;
/* book 2 specification */
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Book2.subject = "Telecom Billing Tutorial";
Book2.book_id = 6495700;
/* print Book1 info */
Console.WriteLine( "Book 1 title : {0}", Book1.title);
Console.WriteLine("Book 1 author : {0}", Book1.author);
Console.WriteLine("Book 1 subject : {0}", Book1.subject);
Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);
/* print Book2 info */
Console.WriteLine("Book 2 title : {0}", Book2.title);
Console.WriteLine("Book 2 author : {0}", Book2.author);
Console.WriteLine("Book 2 subject : {0}", Book2.subject);
46

47
Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the following result:
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Features of C# Structures
You have already used a simple structure named Books. Structures in C# are quite different from that in traditional C or
C++. The C# structures have the following features:

Structures can have methods, fields, indexers, properties, operator methods, and events.

Structures can have defined constructors, but not destructors. However, you cannot define a default
constructor for a structure. The default constructor is automatically defined and cannot be changed.

Unlike classes, structures cannot inherit other structures or classes.

Structures cannot be used as a base for other structures or classes.

A structure can implement one or more interfaces.

Structure members cannot be specified as abstract, virtual, or protected.

When you create a struct object using the New operator, it gets created and the appropriate constructor is
called. Unlike classes, structs can be instantiated without using the New operator.

If the New operator is not used, the fields remain unassigned and the object cannot be used until all the fields
are initialized.
47

48
Class versus Structure
Classes and Structures have the following basic differences:

classes are reference types and structs are value types

structures do not support inheritance

structures cannot have default constructor

In the light of the above discussions, let us rewrite the previous example:
using System;
struct Books
{
private string title;
private string author;
private string subject;
private int book_id;
public void getValues(string t, string a, string s, int id)
{
title = t;
author = a;
subject = s;
book_id = id;
}
public void display()
{
Console.WriteLine("Title : {0}", title);
Console.WriteLine("Author : {0}", author);
Console.WriteLine("Subject : {0}", subject);
Console.WriteLine("Book_id :{0}", book_id);
}
};
48

49

public class testStructure


{
public static void Main(string[] args)
{
Books Book1 = new Books(); /* Declare Book1 of type Book */
Books Book2 = new Books(); /* Declare Book2 of type Book */
/* book 1 specification */
Book1.getValues("C Programming",
"Nuha Ali", "C Programming Tutorial",6495407);
/* book 2 specification */
Book2.getValues("Telecom Billing",
"Zara Ali", "Telecom Billing Tutorial", 6495700);
/* print Book1 info */
Book1.display();
/* print Book2 info */
Book2.display();
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the following result:
Title : C Programming
Author : Nuha Ali
Subject : C Programming Tutorial
49

50
Book_id : 6495407
Title : Telecom Billing
Author : Zara Ali
Subject : Telecom Billing Tutorial
Book_id : 6495700

7. Explain about the classes with constructors and destructors in C#.

When you define a class, you define a blueprint for a data type. This does not actually define any data, but it
does define what the class name means. That is, what an object of the class consists of and what operations can be
performed on that object. Objects are instances of a class. The methods and variables that constitute a class are called
members of the class.
Defining a Class
A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of
curly braces. Following is the general form of a class definition:
<access specifier> class class_name
{
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list)
{
// method body
}
<access specifier> <return type> method2(parameter_list)
50

51
{
// method body
}
...
<access specifier> <return type> methodN(parameter_list)
{
// method body
}
}
Note:
Access specifiers specify the access rules for the members as well as the class itself. If not mentioned, then

the default access specifier for a class type is internal. Default access for the members is private.
Data type specifies the type of variable, and return type specifies the data type of the data the method

returns, if any.

To access the class members, you use the dot (.) operator.

The dot operator links the name of an object with the name of a member.

The following example illustrates the concepts discussed so far:


using System;
namespace BoxApplication
{
class Box
{
public double length; // Length of a box
public double breadth; // Breadth of a box
public double height; // Height of a box
}
class Boxtester
{
51

52
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
double volume = 0.0;

// Store the volume of a box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
Console.WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
52

53
Member Functions and Encapsulation
A member function of a class is a function that has its definition or its prototype within the class definition similar to any
other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class
for that object.
Member variables are the attributes of an object (from design perspective) and they are kept private to implement
encapsulation. These variables can only be accessed using the public member functions.
Let us put above concepts to set and get the value of different class members in a class:
using System;
namespace BoxApplication
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
public void setLength( double len )
{
length = len;
}
public void setBreadth( double bre )
{
breadth = bre;
}
public void setHeight( double hei )
{
height = hei;
}
public double getVolume()
{
53

54
return length * breadth * height;
}
}
class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box();
double volume;
// Declare Box2 of type Box
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}" ,volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
54

55
}
}
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
C# Constructors
A class constructor is a special member function of a class that is executed whenever we create new objects of that
class.
A constructor has exactly the same name as that of class and it does not have any return type. Following example
explains the concept of constructor:
using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line()
{
Console.WriteLine("Object is being created");
}
public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
55

56
}
static void Main(string[] args)
{
Line line = new Line();
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Object is being created
Length of line : 6
A default constructor does not have any parameter but if you need, a constructor can have parameters. Such
constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the
time of its creation as shown in the following example:
using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line(double len) //Parameterized constructor
{
Console.WriteLine("Object is being created, length = {0}", len);
length = len;
}
56

57

public void setLength( double len )


{
length = len;
}
public double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line(10.0);
Console.WriteLine("Length of line : {0}", line.getLength());
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Object is being created, length = 10
Length of line : 10
Length of line : 6
C# Destructors
A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope.
A destructor has exactly the same name as that of the class with a prefixed tilde (~) and it can neither return a value nor
can it take any parameters.

57

58
Destructor can be very useful for releasing memory resources before exiting the program. Destructors cannot be
inherited or overloaded.
Following example explains the concept of destructor:
using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line() // constructor
{
Console.WriteLine("Object is being created");
}
~Line() //destructor
{
Console.WriteLine("Object is being deleted");
}
public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line();
58

59

// set line length


line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
}
}
}
When the above code is compiled and executed, it produces the following result:
Object is being created
Length of line : 6
Object is being deleted
Static Members of a C# Class
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 keyword static implies that only one instance of the member exists for a class. Static variables are used for defining
constants because their values can be retrieved by invoking the class without creating an instance of it. Static variables
can be initialized outside the member function or class definition. You can also initialize static variables inside the class
definition.
The following example demonstrates the use of static variables:
using System;
namespace StaticVarApplication
{
class StaticVar
{
public static int num;
public void count()
{
num++;
}
public int getNum()
59

60
{
return num;
}
}
class StaticTester
{
static void Main(string[] args)
{
StaticVar s1 = new StaticVar();
StaticVar s2 = new StaticVar();
s1.count();
s1.count();
s1.count();
s2.count();
s2.count();
s2.count();
Console.WriteLine("Variable num for s1: {0}", s1.getNum());
Console.WriteLine("Variable num for s2: {0}", s2.getNum());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Variable num for s1: 6
Variable num for s2: 6
You can also declare a member function as static. Such functions can access only static variables. The static functions
exist even before the object is created. The following example demonstrates the use of static functions:
using System;
namespace StaticVarApplication
{
60

61
class StaticVar
{
public static int num;
public void count()
{
num++;
}
public static int getNum()
{
return num;
}
}
class StaticTester
{
static void Main(string[] args)
{
StaticVar s = new StaticVar();
s.count();
s.count();
s.count();
Console.WriteLine("Variable num: {0}", StaticVar.getNum());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Variable num: 3

61

You might also like