0% found this document useful (0 votes)
30 views53 pages

C# Unit - III

Uploaded by

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

C# Unit - III

Uploaded by

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

SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

2 MARKS
1. What is value type?
(May-22)
It includes simple data types such as enum, struct, char, bool, int, float, etc. Value type
variable directly contain data since memory is allocated on stack. Operation on one variable
doesnot affect the other value type variable. It provides efficient access and faster execution by
stack allocation.
2. What is reference type? (May-22)
It includes class types, interface types, delegate types and array types. Reference variable
stores references to objects whereas the data of objects are stored in locations represented by
references. Reference variable points to an object allocated on heap. Reference variable can have
null value. One or more reference variables can be assigned with the same reference of an object.
Hence, operation on one reference variable may affect the object referenced by theother
reference variable.
3. What are types of parameters available?
C# employs four kinds of parameters:
 Value parameters - used to pass the parameters by value
 Reference parameters - used to pass the parameters by reference
 Output parameters - used to pass the results back from a method
 Parameter arrays (using param) - used to pass a variable number of parameters
4. Write a short note on pass by value.
By default, method parameters are passed by value. When a method is invoked,the
values of actual parameters are assigned to the corresponding formal parameters. The value of
the actual parameter that is passed by value to a method is not changed by any changes made to
the corresponding formal parameter within in the body of the method.
Ex:
using System; class
PassBy Value
{
Static int increment(int val)
{
return ++val;
}

U20CSCM02-C# AND .NET PROGRAMMING 1


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

public static void Main()


{
int a = 10;
Console.WriteLine(―Value of a ‐ before calling increment is ―
+ a); Console.WriteLine(―Value returned by increment is ― + increment(a);
Console.WriteLine(‗Value of a –“after calling increment is {0}”, a); }
}
Output:
Value of a - before calling increment is
10Value returned by increment is 11 Value
of a - after calling increment is 10
5. Write a short note on pass by reference.
Unlike a value parameter, a reference parameter does not create a new storagelocation.
Instead, it represents the same storage location as the actual parameter used in the method
invocation. Remember, when a formal parameter is declared as ref, the corresponding argument
in the method invocation must also be declared as ref.
Ex:
Using
System;

Class
passbyref
{
static void increment(ref int val)
{
++val;
}
public static void Main()
{
int a = 10;
Console.WriteLine(“Value of a ‐ before calling increment is ”+ a); increment(

ref a);

Console.WriteLine(“Value of a - after calling increment is {0}”, a);

U20CSCM02-C# AND .NET PROGRAMMING 2


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

}
}
Output:
Value of a - before calling increment is
10Value of a - after calling increment is
11
6. Write a short note on output parameters.
Output parameters are used to pass results back to the calling method. This is achieved by
declaring the parameters with an out keyword. Similar to reference parameter, an output
parameter does not create a new storage location. Instead, it becomes an alias to the
parameter in the calling method. When a formal parameter is declared as out, thecorresponding
actual parameter in the calling method must also be declared as out. Ex:
using
System;
class

Output
{
static void addition (int a , int b, out int result)
{
result = a + b;
}
public static void Main()
{
int x = 5, y = 8,
sum; addition(x,
y, out sum);
Console.WriteLine(―The sum of {0} and {1} is {2}‖, x, y, sum);
}
}
7. What is a class?
A class is essentially a description of how to construct an object that contains fieldsand
methods. It provides a sort of template for an object and behaves like a basic data

U20CSCM02-C# AND .NET PROGRAMMING 3


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

type such as int. Classes provide a convenient approach for packing together a group oflogically
related data items and functions that work on them.
8. List out reference data types?
The reference types can also be divided into two
groups:User‐defined (or complex) types
Predefined (or simple) types
User‐defined reference types refer to those which are defined by the user using
predefined type. They include,

Classes

Interfaces

Delegates

Arrays
Predefined reference types include two data types:object type,String type

9. Write a note on encapsulation?


Encapsulation provides the ability to hide the internal details of an object from its users. The
outside user may not be able to change the state of an object directly. However, the state of an
object may be altered indirectly using what are known accessor and mutator methods. Theconcept
of encapsulation is also known as data hiding or information hiding.

10. What is inheritance?


Inheritance is the concept used to build new classes using the existing class definitions.
Through inheritance a class can be modified easily. The original class is known as base or
parent class and the modified one is known as derived class or subclass or child class. The
concept of inheritance facilitates the reusuability of existing code and thus improves the integrity
of programs and productivity of programmers.
11. What is polymorphism? (May-22)
Polymorphism is the ability to take more than one form. The behavior of the method
dependsupon the types of data used in the operation. This is extensively used while
implementing inheritance.

U20CSCM02-C# AND .NET PROGRAMMING 4


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

12. What is the Characteristic of Inheritance?


1. A derived class extends its direct base class. It can add new members to those
itinherits. However, it cannot change or remove the definition on an inherited member.
2. Constructor and destructors are not inherited. All other members, regardless of
theirdeclared accessibility in base class, are inherited.
3. All instance of a class contains a copy of all instance fields declared in the classand its
baseclasses.
4. A derived class can hide an inherited member.
5. A derived class can override an inherited member.

13. Advantages of Inheritance


1. Reuse the existing code and extend the functionality.
2. Add new members to the derived class to specialize the class.
3. replace the implementation of existing methods by overriding a method that already exists in
the base class. use of virtual and override methods help to exhibit polymorphic behavior.
4. Organize software components into categories and subcategories resulting in classification
of software. Classification is the most widely accepted use of inheritance although other
mechanisms may also be used for classification.
14. List out the member access modifiers in C# (APR 2012)
private - Member is accessible only within the class containing the member.
public - Member is accessible from anywhere outside the class as well. It is alsoaccessible
in derived classes.
protected - Member is visible only to its own class and its derived class.
internal - Member is available within the assembly or component that is being createdbut not
tothe clients of the component.
protected internal - Available in the containing program or assembly and in the derived classes.

15. What are the features of a constructor?


The name of the constructor is the same as the class.
A constructor does not return any value and hence does not have a return type. The
formal parameters define the signature of the constructor. A constructor initializer cannot access
the object being created. A constructor is called when an object is

U20CSCM02-C# AND .NET PROGRAMMING 5


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

created.
16. What is default constructor?
A public parameter less constructor is called default constructor. And it is implicitly
declared for any class. Even though there is no constructor in the class this default constructor
will be invoked and initializes the member with default value of that type.
Simply, the process called instantiation is done through calling the constructor only.
17. What is the use of private constructors?
C# does not have global variables or constants. All declarations must be containedin a
class. But using static members this can be achieved some what. Such classes are never required
to instantiate objects because; object is not needed to access the static members of a class.
Creating objects for such classes may be prevented by usingprivate constructor to the class.
18. What is copy constructor?
A copy constructor creates an object by copying variables from another object.But
there is no copy constructor provided in C#. It should be defined by the programmer.

Ex:

public Point(Point pt)


{x
=pt.x;
y=
pt.y;
}
The copy constructor is invoked when instantiating the object of type Point. For
example,

Point p2 = new Point(p1);


19. What is destructor?
A destructor is opposite to a constructor. It is a method called when an object is no more
required. The name of the destructor is the same as the class name and is preceded by a tilde (~).
Like constructors, a destructor has no return type.
20. What are the features of a destructor?
The name of the destructor is same as the class name. The name is preceded by ~.

U20CSCM02-C# AND .NET PROGRAMMING 6


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

It is always public. There is no parameter in the signature. There is no return type.


21. What are properties?
Properties have the same capabilities as accessor methods, but are much more elegant
and simple to use. Using a property a programmer can get access to data members easily. These
are sometimes referred as ―smart fields‖.
Ex:
Class TestProp
{
Private int n;
Public int number //property defines getter and setter methods
{
get
{
return n;
}
set
{
number = value;
}
}
}
22. What is the containment inheritance?
If an object contains another object in it, it is called as containment inheritance.
This represents the ―has‐ a‖ relationship. Ex:
class A
{
int a;
}
class B
{
int b;
A aa; // object aa is contained in object of B
….

U20CSCM02-C# AND .NET PROGRAMMING 7


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

}
23. What are the constraints on the accessibility of members and classes in C#?
1. The direct base class of a derived class must be at least as accessible as the
derived classitself.
2. Accessibility domain of a member is never larger that that of the class containing it.
3. The return type of method must be at least as accessible as the method itself.
24. What are the Characteristics of the Override?
1. An override declaration may include the abstract modifier.
2. It is an error for an override declaration to include new or static or virtual modifier.
3. The overridden base method cannot be static or nonvirtual.
4. The overridden base method cannot be a sealed method. What is the use of abstract
modifierwith class?
The abstract is a modifier and when used to declare a class indicates that the class cannot
be instantiated. Only its derived classes can be instantiated. So, the object can‘t be created for an
abstract class.
25. What is polymorphism? What are the methods available to do that?
Polymorphism means ―one name, many forms‖. Essentially, polymorphism is the
capability of one object to behave in multiple ways. It can be achieved in two ways:
1. Operation Polymorphism can be achieved by using overloaded methods.
2. Inclusion Polymorphism can be achieved by using virtual methods.
26. What is operation polymorphism?
Operation polymorphism is implemented using overloaded methods and operators. The
overloaded methods are selected for invoking by matching arguments, in terms of number, type
and order. This information is known to the compiler at the time of compilation and,
therefore, the compiler is able to select and bind the appropriate method to the object for a
particular call at compile time itself. This process is called early binding, or static binding,
or static linking. It is also known as compile time polymorphism.
27. Write a note on interface.
An interface can contain one or more methods, properties, indexers, and events but
none of them are implemented in the interface itself. It is the responsibility of the class that
implements the interface to define the code for implementation of these members.
Syntax:

U20CSCM02-C# AND .NET PROGRAMMING 8


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

interfaceInterfaceName
{
Member declarations;
}
28. What are indexers?
Indexers are location indicators and are used to access class objects, just like accessing
elements in an array. They are useful in cases where a class is a container for other objects.
These are referred as ―smart arrays‖.
Ex:
publicint this [int index]
{
get
{
//return desired data
}
set
{
//set desired data
}}
29. Differentiate indexer from property.
A property can be static member, whereas an indexer is always an instance member A get
acccessor of a property corresponds to a method with no parameters, whereas a get accessor of
an indexer corresponds to a method with the same formal parameter list as the indexer.

A set accessor of a property corresponds to a method with a single parameter named


value, whereas a set accessor of an indexer corresponds to a method with the same formal
parameter list as the indexer, plus the parameter named value. It is an error for an indexer to
declare a local variable with the same name as an indexer parameter. The indexer takes an index
argument and looks like array. The indexer is declared using the name this.
30. Define Delegate? (APR 2012)
It is an Event handling mechanism of .NET. To raise events, a class must define one
delegate per event type. To handle events, types must implement one event handler per event
type. Delegates can reference both instance and static methods. C# uses the

U20CSCM02-C# AND .NET PROGRAMMING 9


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

delegate keyword.
31. What are steps involved in using delegates in a C# program?
1. Delegate declaration
2. Delegate methods definition

3. Delegate instantiation
4. Delegate invocation
32. What is an error?
Error is mistakes that can make a program go wrong. An error may produce an incorrect
output or may terminate the execution of the program abruptly or even may cause the system to
crash. There are two types of error:
1. Compiler‐time errors
2. Run‐time errors
33. Write some examples for run‐time errors.
1. Dividing an integer by zero
2. Accessing an element that is out of bounds of an array
3. Trying to store a value into an array of an incompatible class or type
4. Passing a parameter that is not in a valid range or value for a method
5. Attempting to use a negative size for an array.
34.What is Exception?
When an unplanned or unexpected event occurs, an associated exception object isthrown.
The exception will be caught by an exception handler at some level and

appropriate action taken. A fatal exception—catastrophic error—is an event that cannot beproperly
handled to allow the application to continue.
35.What is Exception handling?
Process of intercepting—trapping—an exception and acting appropriately in response.
36.What are tasks involved in exception handling?
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
37. Differentiate Property and Indexer
Property
A property is identified by its name

U20CSCM02-C# AND .NET PROGRAMMING 10


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

A property is accessed through the


property nameA property can be static.
Indexer
An indexer is identified by its signature
An indexer element is accessed through the subscripted expression with theobject
nameas the array name.
Indexer is always as instance member
38. What is Override?
Supercede an instance field or virtual method in a base class with a newdefinition of
that member in the derived class (subclass).

39. Distinguish clearly between value type and reference type in C#


(Nov’15)(Apr’16)(Nov’13)
s.no Value type Reference type
1 A Value Type holds the data withinits Reference Type contains a pointer to another
own memory allocation memory location that holds the real data.

2 Value Type variables are stored in the Reference Type variables are stored in the
stack. heap

3 e.g. e.g.
int x = 10; int[] iArray = new int[20];
Here the value 10 is stored in an areaof In the above code the space required for the 20
memory called the stack. integers that make up the array is allocatedon the
heap.

40. What is inclusion polymorphism? (Apr’16)


Inclusion Polymorphism is achieved through the use of virtual functions. It isknown
asRuntime polymorphism, dynamic binding and late binding.
The following code snippet shows how to implement inclusionpolymorphism
in C#.using System;

class Maruthi
{
public virtual void Display()

U20CSCM02-C# AND .NET PROGRAMMING 11


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

{
Console.WriteLine("Maruthi Car");
}
}
class Esteem:Maruthi
{
public override void Display()
{
Console.WriteLine("Maruthi Esteem");
}
}
class Zen:Maruthi
{
public override void Display()
{
Console.WriteLine("Maruthi Zen");
}
}
class Inclusion
{
public static void Main()
{
Maruthi m=new
Maruthi();
m=new
Esteem();
m.Display(); // prints Maruthi
Esteemm=new Zen();
m.Display(); // prints Maruthi Zen
}
}
in inclusion polymorphism, the multiple forms occur at class level.
40. List down the various types of Inheritance
(Apr’15)

U20CSCM02-C# AND .NET PROGRAMMING 12


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Types of inheritance
 Single Inheritance
 Hierarchical Inheritance
 Multilevel Inheritance
 Multiple Inheritance
 Hybrid Inheritance

5 MARKS
1. Explain Inheritance in C# (May-22)
Inheritance is the ability to derive new classes from existing ones. A derived class (―sub class‖)
inherits the instance variables and method of the base class (―parent class‖), and may add new
instance variables and methods. Inheritance defines a hierarchical relationship among classes
wherein one class shares the attributes and method defined in one or more classes.
Types of inheritance
 Single Inheritance
 Hierarchical Inheritance
 Multilevel Inheritance
 Multiple Inheritance
 Hybrid Inheritance
Examples For various types of inheritance
 Single
Inheritanc
e
Example:
Animal

Dog
 Hierarchical
Inheritance
Example:

U20CSCM02-C# AND .NET PROGRAMMING 13


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Animal

Dog Cat Cow


 Multiple Inheritance
Example: Horse Donkey

Mule
 Multilevel
Inheritance
Example: Animal

Dog

Bull Dog
 Hybrid Inheritance
It is a combination of all the above types of
InheritanceExample: Animal

Mammal Reptile

Frog Snake
Note: C# does not directly support Multiple Inheritance. This concept is implemented using
Interfaces.
Rules of Inheritance:
 A class can only inherit from one class (known as single Inheritance)
 A subclass is guaranteed to do everything the base class can do.
 A subclass inherits members from its class and can modify or add to its
behavior andproperties.
 A subclass can define members of the same name in the base class, thus hidingthe
baseclass members.
 Inheritance is transitive (i.e., class A inherits from class B, including what B

U20CSCM02-C# AND .NET PROGRAMMING 14


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

inheritedfrom class C).


All class inherits from the highest object class in the inheritance hierarchy
 Private members and constructors are not inherited by subclasses.
Example for Inheritance:
Class BirthdayParty: HappyBirthday
{
Public BirthParty ( ): base ( )
{
}
Public string get party (boolhaveParty)
{
if (have Party ==true)
{
return “Enjoy your Party!”;
}
else
}
return “Sorry- no party for you!”;
}} }
2. Explain Interface In Detail. (Nov 2013) (Apr 2013)(Nov 2018)
 An interface defines a contract by specifying a set of method prototypes specifying a
setof method prototypes to which each class that implements it must adhere.
 An interface in 100% abstract class.
 An interface provides a form for a class but now how to implement it.
 An interface defines what a class can do but now how the class will do it.
Rules on interface:
 An interface can inherit from multiple base interfaces. Interfaces can be implemented by
any class. An interface cannot implement any data type. An interface cannot be
instantiated. Interface can contain methods, properties, events and indexers. The
interface itself does not provide implementations for the members that it defines.
 The interface merely specifies that members must supply classes or struct to implement
the interface. A class or struct can implement several interfaces, thus

U20CSCM02-C# AND .NET PROGRAMMING 15


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

enabling multiple inheritances. A class that implements an interface partially must be


declared abstract. New, public, protected, internal and private are valid interfacemodifiers.
Implementing an Interface:
Implementing an Interface means providing implementations for its methods. Interfaces are
implemented using a ―;‖. Rules for implementing the interface methods are:
1. Must have the same signature and return type.
2. Cannot narrow the method accessibility Interface methods are implicitlypublic.

Example:

Public abstract class AccountInfo


{
Private double balance;
{
Get
{
Return balance;
}
Set
{
Balance = value;
}
}
Public abstract void PrintAccountInfo ();
}
Public class Savings: AccountInfo, BankOperations
{
Public void withdraw (double amount)
{
Balance = Balance-amount;
}
Public void Deposit (double amount)
{

U20CSCM02-C# AND .NET PROGRAMMING 16


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Balance = Balance + amount;


}
Public double BalanceInquiry ()
{
Return Balance;
}
Public void PrintAccountInfo ()
{
Console.Writeline (―Account Balance: ― +Balance);
}}
Public interface BankOperations
{
Public void Withdraw (double amount);

Public void Deposit (double amount);

Public double BalanceInquiry ();


}
Public class BankApp
{
Public static void main (String [] args)
{
Savings pesoAcct = new Savings ();
pesoAcct.Balance = 500;
pesoAcct.PrintAccountInfo ();
pesoAcct.Deposit (300);
pesoAcct.Withdraw (50);
pesoAcct.Console.WriteLine (―updated Balance:‖ +pesoAcct.BalanceInquiry ());

RESULT:
Account Balance: 500.0
Updated Balance: 750.0
3. Differentiate Abstract Class vs Interface:
ABSTRACT CLASS VS INTERFACE
 An Interface is useful because any class can implement it. But an interface,

U20CSCM02-C# AND .NET PROGRAMMING 17


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

compared to an abstract class, is like a pure API specification and contains no


implementation.
 If another method is added in an Interface, all classes that implement, that interfacewill be
broken.
 A good Implementation of both is to create an interface and let the abstract class
implement it. So when there is a need for adding methods, it can be safely added to the
abstract class itself rather than the Interface.
 Use Interfaces when a certain method needs to be forcibly overridden/enforced by a class.
4. Explain Method overloading with example: (May-22)
 Static Polymorphism is also called as Method overloading.
 Method Overloading is the process of declaring methods with the same name
butdifferent parameter types.
 Multiple methods are permitted in a class provided their signatures are unique.
 A method can be overloaded in the same class or in a sub class.
 Which overloaded method to call is based on reference type and decided at compiletime.
 Method Overloading is also known as Compile Time Polymorphism.
RULES FOR METHOD OVERLOADING:
 Overloaded methods must change the arguments list.
 Overloaded methods can change the return type.
 Overloaded methods can change the access modifiers.
 Overloaded methods can declare new or broader checked
exceptions.

Example for Method Overloading:

Using System; Namespace


ProgramCall
{
Class class1
{
Public int Sum (intA, int B)
{
Return A+B;

U20CSCM02-C# AND .NET PROGRAMMING 18


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

}
Public float Sum (intA, float B)
{
Return A+B;
}
Class class2: class1
{
Public int Sum ()int A, int B, int C)
{
Return A+B+C;
}}
Class Mainclass
{
Static void Main()
{
Class2 obj = new class2 ();

Console.Writeline (obj.Sum (10, 20));


Console.WriteLine (obj.Sum (10, 15.70f));
Console.WriteLine (obj.Sum (10, 20, 30));
Console.ReadLine ();
}}}
5. Explain Method overriding with example:
Dynamic Polymorphism is also called as Method Overriding.
Method Overriding allows a sub class to redefine methods of the same name fromthe
superclass.
The key benefit or overriding is the ability to define/defer behavior specific to sub
classes.Which overridden method to call is based on object type and decided at runtime.
Method Overriding is also known as runtime
polymorphism.
RULES OF METHOD OVERRIDING:
- An overridden method must have
 The same name

U20CSCM02-C# AND .NET PROGRAMMING 19


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

 The same number of parameters and types.


 The same return type as the overridden method.
- Overriding a method cannot narrow the method access level defined in the
overriddenmethod.
- Methods declared as private, static, or sealed cannot be overridden.
- For a method to be overridable without any compilation error/warning, itshould
bemarked as virtual or abstract or override.
- A static method cannot override an instance
method.
Example for Method Overriding:

Using System;
Class Square
{
Public double x;
Public Square (double x)
{
this.x = x;
}
Public Virtual Double Area()
{
return x*x;
}}
Class cube: Square
{
Public cube (double x): base (x)
{
}
Public override double Area ()
{
return (6*(base.Area());
}}
Public Static void Main ()
{

U20CSCM02-C# AND .NET PROGRAMMING 20


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

double x =5.2;
Square S = new Square (x);Square C =
new cube (x);
Console.WriteLine (―Area of Square = ―, S.Area ()); Console.WriteLine
(―Area of cube =‖, C.Area ());
}}

OUTPUT:
Area of Square
= 27.04

Area of Cube
= 162.24
OVERLOADING VS OVERRIDING

CRITERIA OVERLOADED METHOD OVERRIDING METHOD


Argument List Different Same
Return Type Can Change Same
Access level Can Change Cannot be narrower
Invocation Based on reference type and Based on object type and
decided at Compile Time decided at Run Time.

6. Explain Collections In C#
C# collection is a class that provides more advanced mechanisms for gatheringgroups
ofobjects.
C# COLLECTIONS CLASSES:

The C# collection classes are a set classes designed specifically for grouping together objects and
performing tasks on them. A number of collection classes are available with C#and we will be
looking at the key classes that are available.

Creating C# List Collection – List <T> and ArrayList


Both the List <T> and ArrayList classes have properties very similar to C# Arrays. One
key advantage of these classes over arrays is that they can grow and shrink as the number of
stored objects changes.
The List <T> class is contained with the System.Collections.Generic namespaces
while the ArrayList class is contained within the System.Collections namespace.

U20CSCM02-C# AND .NET PROGRAMMING 21


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

The syntax for creating a List <T> Collection is as follows.


List <type> name = new List <type> ();
An ArrayList object is created in a similar manner, although without the type argument.
ArrayList name = new ArrayList ();
With the above syntax in mind we can now create a List <T> object called ColorList.Using
System;
Using System.Collections.Generic;Publicclass
Lists
{
Static void Main ()
{
List <string>colorlist = new List <string> ();
}}
Adding Items to Items:
Once a List object has been created there are a number of methods which may be called to
perform tasks on the List. One such method is the Add () method which, as the name suggests,
isused to add items to the List Object.
List <String>colorlist = new List
<string> ();colorlist.Add (―Red‖);
colorlist.Add(―Green‖);
colorlist.Add(―Yellow‖);
colorlist.Add(―Purple‖);
colorlist.Add(―Orange‖);
Accessing List Items:
Individual items in a list may be accessed using the index value of the item (keeping in mind
thatthe first item is index 0, the second index 1 and so on). The index value is placed in square
brackets after the list name. For example, to access the second item in the colorlist object.

Console.WriteLine (colorlist[1]);
A list item value can similarly be changed using the index combined with theassignmentoperator.
For example, to change the color from Yellow to Indigo,
Colorlist [2] =‖Indigo‖;
All the items in a list may be accesses using a foreach loop. For
example:foreach (string color in colorlist)
{

U20CSCM02-C# AND .NET PROGRAMMING 22


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Console.WriteLine (color);
}
When compiled and executed, the above code will output each of the color strings inthe
colorstrings in the colorlist objects:
Colorlist.Remove (―red‖);
It is important to note that items in a List may be duplicated. In the case of duplicateditems,
theRemove () method will only Remove the first matching instances

7. Explain Exception Handling In Detail. (Nov2013) (Nov 2012) (Apr’14)


 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
exceptionsare anomalies that occur during the execution of a program. They can be
because of user, logic or system errors. If a user does not provide a mechanism to handle
these anomalies, the .NET run time environment provides a default mechanism, which
terminates the program execution.
 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 general form try – catch finally in C# is shown below.

Try
{
//statements which 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 appropriatecatch
block and later to the finally block.
 But in C#, both catch and finally blocks are optional. The try block can exist either

U20CSCM02-C# AND .NET PROGRAMMING 23


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

with one or more catch blocks as a finally block or with catch and finally blocks.
 If there is no exception occurred inside the try block, the control directly transfers to
finally block. We can say that the statements inside the finally block is executed always.
Note that it is an error to transfer control out of a finally block by using break, continue,
return or goto.
 In a C#, exceptions are nothing but objects of the type exception. The Exception is the
ultimate Base class for any exceptions in C#.
 The C# itself provides couple of standard exceptions. Or even Exception class or one of
the standard derived classes of exception class like DivideByZeroException and
ArgumentException etc.
Example for Exception Handling:
Using System;

Class Myclient;
{
Public static void Main ()
{
int x=0; int div =0;try
{
Div =100/x;
Console.Writeline (―Not executed Line‖);
}
Catch (DivideByZeroException de)
{
Console.Writeline (―Exception Occurred‖);
}
Finally
{
Console.WriteLine (―Finally Block‖);
}
Console.WriteLine (―Result is {0}‖, div);
}}

U20CSCM02-C# AND .NET PROGRAMMING 24


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

10 MARKS
1. Write a short note on interface properties and interface indexers.

Like a class, Interface can have methods, properties, events, and indexers as its members. But
interfaces will contain only the declaration of the members. The implementation of theinterface’s
members will be given by class who implements the interface implicitly or explicitly.
 Interfaces specify what a class must do and not how.
 Interfaces can’t have private members.
 By default all the members of Interface are public and abstract.
 The interface will always defined with the help of keyword ‘interface‘.
 Interface cannot contain fields because they represent a particular implementation ofdata.
 Multiple inheritance is possible with the help of Interfaces but not with classes.

Syntax for Interface Declaration:


interface<interface_name >
{
// declare Events
// declare indexers
// declare methods
// declare properties
}
Syntax for Implementing Interface:

class class_name : interface_name


To declare an interface, use interface keyword. It is used to provide total abstraction. That means
all the members in the interface are declared withthe empty body and are public and abstract by
default. A class that implements interface must implement all the methods declared in the
interface.
Example :

Public abstract class AccountInfo


{
Private double balance;
{
Get
{
Return balance;

U20CSCM02-C# AND .NET PROGRAMMING 25


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

}
Set
{
Balance = value;
}
}
Public abstract void PrintAccountInfo ();
}
Public class Savings: AccountInfo, BankOperations
{
Public void withdraw (double amount)
{
Balance = Balance-amount;
}
Public void Deposit (double amount)
{
Balance = Balance + amount;
}
Public double BalanceInquiry ()
{
Return Balance;
}
Public void PrintAccountInfo ()
{
Console.Writeline (―Account Balance: ― +Balance);
}}
Public interface BankOperations
{
Public void Withdraw (double amount);

Public void Deposit (double amount);

Public double BalanceInquiry ();


}
Public class BankApp

U20CSCM02-C# AND .NET PROGRAMMING 26


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

{
Public static void main (String [] args)
{
Savings pesoAcct = new Savings ();
pesoAcct.Balance = 500;
pesoAcct.PrintAccountInfo ();
pesoAcct.Deposit (300);
pesoAcct.Withdraw (50);
pesoAcct.Console.WriteLine (―updated Balance:‖ +pesoAcct.BalanceInquiry ());

RESULT:
Account Balance: 500.0
Updated Balance: 750.0

2.Explain about Encapsulation in C#:


Encapsulation is defined 'as the process of enclosing one or more items within a physical or logical
package'. Encapsulation, in object oriented programming methodology, prevents access to
implementation details.
Abstraction and encapsulation are related features in object oriented programming. Abstraction allows
making relevant information visible and encapsulation enables a programmer to implement the
desired level of abstraction.
Encapsulation is implemented by using access specifiers. An access specifier defines the scope and
visibility of a class member. C# supports the following access specifiers −

Public
Private
Protected
Internal
Protected internal
Public Access Specifier
Public access specifier allows a class to expose its member variables and member functions to other
functions and objects. Any public member can be accessed from outside the clas

Using system;
namespace RectangleApplication {
class Rectangle {
//member variables
public double length;
public double width;

public double GetArea() {

U20CSCM02-C# AND .NET PROGRAMMING 27


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

return length * width;


}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle

class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Length: 4.5
Width: 3.5
Area: 15.75
In the preceding example, the member variables length and width are declared public, so theycan be
accessed from the function Main() using an instance of the Rectangle class, named r.
The member function Display() and GetArea() can also access these variables directly withoutusing
any instance of the class.
The member functions Display() is also declared public, so it can also be accessedfrom
Main() using an instance of the Rectangle class, named r.
Private Access Specifier
Private access specifier allows a class to hide its member variables and member functions from other
functions and objects. Only functions of the same class can access its private members. Even an
instance of a class cannot access its private members.
The following example illustrates this −

using System;

namespace RectangleApplication {
class Rectangle {
//member variables
private double length;
private double width;

public void Acceptdetails() {


Console.WriteLine("Enter Length: ");
length = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter Width: ");

U20CSCM02-C# AND .NET PROGRAMMING 28


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

width = Convert.ToDouble(Console.ReadLine());
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle

class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Enter Length:
4.4
Enter Width:
3.3
Length: 4.4
Width: 3.3
Area: 14.52
In the preceding example, the member variables length and width are declared private, so they cannot
be accessed from the function Main(). The member functions AcceptDetails()
and Display() can access these variables. Since the member functions AcceptDetails() and Display()
are declared public, they can be accessed from Main() using an instance of the Rectangle
class, named r.
Protected Access Specifier
Protected access specifier allows a child class to access the member variables and member functions
of its base class. This way it helps in implementing inheritance.
Internal Access Specifier
Internal access specifier allows a class to expose its member variables and member functions to other
functions and objects in the current assembly. In other words, any member with internal access specifier
can be accessed from any class or method defined within the application in which the member is
defined.
The following program illustrates this –

using System;

namespace RectangleApplication {

U20CSCM02-C# AND .NET PROGRAMMING 29


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

class Rectangle {
//member variables
internal double length;
internal double width;

double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle

class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Length: 4.5
Width: 3.5
Area: 15.75
In the preceding example, notice that the member function GetArea() is not declared with any access
specifier. Then what would be the default access specifier of a class member if we don't mention any? It
is private.
Protected Internal Access Specifier
The protected internal access specifier allows a class to hide its member variables and member
functions from other class objects and functions, except a child class within the same application.
This is also used while implementing inheritance.

3.Explain about Inheritance and type of Inheritance in C# :


In C#, inheritance allows us to create a new class from an existing class. It is a key feature of
Object-Oriented Programming (OOP).The class from which a new class is created is known
as the base class (parent or superclass). And, the new class is called derived class (child or
subclass).

U20CSCM02-C# AND .NET PROGRAMMING 30


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

The derived class inherits the fields and methods of the base class. This helps with the code
reusability in C#.

Example:

Class BirthdayParty: HappyBirthday


{
Public BirthParty ( ): base ( )
{
}
Public string get party (boolhaveParty)
{
if (have Party ==true)
{
return “Enjoy your Party!”;
}
else
}
return “Sorry- no party for you!”;}} }

protected Members in C# Inheritance:

When we declare a field or method as protected, it can only be accessed from the same class
and its derived classes.
Example:

using System;

namespace Inheritance {

// base class

class Animal {

protected void eat() {

Console.WriteLine("I can eat");

U20CSCM02-C# AND .NET PROGRAMMING 31


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

}}

// derived class of Animal

class Dog : Animal {

static void Main(string[] args) {

Dog labrador = new Dog();

// access protected method from base class

labrador.eat();

Console.ReadLine(); }}}

OUTPUT:

I can eat

Types of inheritance
 Single Inheritance
 Hierarchical Inheritance
 Multilevel Inheritance
 Multiple Inheritance
 Hybrid Inheritance
Examples For various types of inheritance
 Single
Inheritane
Example:
Animal
Dog

U20CSCM02-C# AND .NET PROGRAMMING 32


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

 Hierarchical
Inheritance
Example:

Animal

Dog Cat Cow


 Multiple Inheritance
Example: Horse Donkey

Mule
 Multilevel
Inheritance
Example: Animal

Dog

Bull Dog
 Hybrid Inheritance
It is a combination of all the above types of
InheritanceExample:

Animal Mammal

Reptile

Frog Snake
Note: C# does not directly support Multiple Inheritance. This concept is implemented usingInterfaces.

U20CSCM02-C# AND .NET PROGRAMMING 33


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Rules of Inheritance:
 A class can only inherit from one class (known as single Inheritance)
 A subclass is guaranteed to do everything the base class can do.
 A subclass inherits members from its class and can modify or add to its
behavior andproperties.
 A subclass can define members of the same name in the base class, thus hidingthe
baseclass members.
 Inheritance is transitive (i.e., class A inherits from class B, including what B
inheritedfrom class C).
All class inherits from the highest object class in the inheritance hierarchy

 Private members and constructors are not inherited by subclasses.

4. Explain Poymorphism In Detail. (Apr 2012) (Nov 2012)


Polymorphism is the ability of different objects to respond to the same
message indifferent ways.
This means that different objects can have very different method
implementations for thesame message.
Polymorphism is derived from 2 Latin words ―Poly‖ – ―many‖ & ―morph‖ –
―forms‖
Polymorphism is the ability of objects belonging to different types to respond to
methodsof the same name, each one according to the appropriate type – specific
behavior.
Polymorphism can be classified into two types.
Static Polymorphism
Dynamic Polymorphism
METHOD OVERLOADING:
Static Polymorphism is also called as Method overloading.
Method Overloading is the process of declaring methods with the same name
butdifferent parameter types.
Multiple methods are permitted in a class provided their signatures are unique.
A method can be overloaded in the same class or in a sub class.
Which overloaded method to call is based on reference type and decided at compiletime.
Method Overloading is also known as Compile Time Polymorphism.

U20CSCM02-C# AND .NET PROGRAMMING 34


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

RULES FOR METHOD OVERLOADING:


Overloaded methods must change the arguments list.
Overloaded methods can change the return type.
Overloaded methods can change the access modifiers.
Overloaded methods can declare new or broader checked
exceptions.

Example for Method Overloading:

Using System; Namespace


ProgramCall
{
Class class1
{
Public int Sum (intA, int B)
{
Return A+B;
}
Public float Sum (intA, float B)
{
Return A+B;
}
Class class2: class1
{
Public int Sum ()int A, int B, int C)
{
Return A+B+C;
}}
Class Mainclass
{
Static void main()
{
Class2 obj = new class2 ();

Console.Writeline (obj.Sum(10, 20));


Console.WriteLine (obj.Sum (10, 15.70f));

U20CSCM02-C# AND .NET PROGRAMMING 35


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Console.WriteLine (obj.Sum (10, 20, 30));


Console.ReadLine ();
}}}
METHOD OVERRIDING:
Dynamic Polymorphism is also called as Method Overriding.
Method Overriding allows a sub class to redefine methods of the same name fromthe
superclass.
The key benefit or overriding is the ability to define/defer behavior specific to sub
classes.Which overridden method to call is based on object type and decided at runtime.
Method Overriding is also known as runtime
polymorphism.RULES OF METHOD OVERRIDING:
- An overridden method must have
 The same name
 The same number of parameters and types.
 The same return type as the overridden method.
- Overriding a method cannot narrow the method access level defined in the
overriddenmethod.
- Methods declared as private, static, or sealed cannot be overridden.
- For a method to be overridable without any compilation error/warning, itshould
bemarked as virtual or abstract or override.
- A static method cannot override an instance
method.
Example for Method Overriding:

Using System;
Class Square
{
Public double x;
Public Square (double x)
{
this.x = x;
}

U20CSCM02-C# AND .NET PROGRAMMING 36


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Public Virtual double Area()


{
return x*x;
}}
Class cube: Square
{
Public cube (double x): base (x)
{
}
Public override double Area ()
{
return (6*(base.Area());
}
}
Public Static void Main ()
{
double x =5.2;
Square S = new Square (x);Square C =
new cube (x);
Console.WriteLine (―Area of Square = ―, S.Area ()); Console.WriteLine
(―Area of cube =‖, C.Area ());
}}

OUTPUT:
Area of Square
= 27.04Area of
Cube = 162.24
OVERLOADING VS OVERRIDING

CRITERIA OVERLOADED METHOD OVERRIDING METHOD


Argument List Different Same
Return Type Can Change Same
Access level Can Change Cannot be narrower

U20CSCM02-C# AND .NET PROGRAMMING 37


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Invocation Based on reference type and Based on object type and


decided at Compile Time decided at Run Time.

5.Explain Abstract Classes In Detail.


An abstract class is a class that provides common behavior across a set of subclasses, but it
not itself designed to have instances of its own.
- A class that indicates certain behavior but allows its subclass to provide implementation.
- A class designed only as a parent from which subclass may be derived, but which is not
itself suitable for instantiation
- A class often used to ―abstract out‖ incomplete sets of features which may then be shared
by a group of sibling sub-class which add different variations of the missingpieces.
Rules on abstract classes:
 An abstract class cannot be instantiated and an abstract class may contain abstract
methods and properties.
 A class with at least one abstract method must be declared as an abstract class.
 A non abstract class derived from an abstract class must include actual implementations
of all inherited abstract methods and properties, thereby overriding those abstract
members.
 A class that has at least one abstract method. Whether declared or inherited from an
abstract class, must be declared abstract.
 Use the abstract modifier in a method or property declaration to indicate that the method
or property does not contain implementation. Abstract method declarations are
onlypermitted in abstract classes.
Example for abstract classes:
Using system;
Using system.Collection.Generic;

Using system.Ling;
Using system.Text;
Namespace console application 6
{

U20CSCM02-C# AND .NET PROGRAMMING 38


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Abstract public class Bank Account


{
Abstract public void withdrawal (double dwithdrawal);
}
Public class savings Account: BankAccount
{
Override public void withdrawal (double dwithdrawal);
{
Console.WriteLine (“Call to saving Account.withdrawal ( ) {0}”,
dwithdrawal);
}
}
Public class checking Account: BankAccount
{
Override public void withdrawal (double dwithdrawal)
{
Console.WriteLine (“call to checking Account.dwithdrawal ( ) {0}”,
dwithdrawal);
}
}
Class program
{
Static void main (string [ ] args)
{
SavingsAccountsa =new SavingsAccount ( );
Sa.withdrawal (1000);
CheckingAccountca = new CheckingAccount ( );
ca.withdrawal (2000);
Console.ReadLine ( );
}
}
}
Snippet:

Using system;

U20CSCM02-C# AND .NET PROGRAMMING 39


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

// Abstract class Abstract class


MyBaseC
{
Protected int x= 100;Protected int y=
150;
// Abstract method Public abstract
voidMyMethod ( );
// Abstract Property Public abstract intGet x
{
Get;
}
}
Class MyDerivedc: MyBaseC
{
Public override void MyMethod ( )
{ X++;
}
// overriding property Public overrideint
Get x
{
Get
{
Return x+10;
}}

Public static void main ( )


{
MyDerivedC mc = new MyDerivedC ( );
mc.MyMethod ( );
Console.WriteLine (―x= {0}‖, mc.Get x);
}
}

U20CSCM02-C# AND .NET PROGRAMMING 40


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

6.Explain Collections In C#
C# collection is a class that provides more advanced mechanisms for gatheringgroups
ofobjects.
C# COLLECTIONS CLASSES:

The C# collection classes are a set classes designed specifically for grouping together objects and
performing tasks on them. A number of collection classes are available with C#and we will be
looking at the key classes that are available.

Creating C# List Collection – List <T> and ArrayList


Both the List <T> and ArrayList classes have properties very similar to C# Arrays. One
key advantage of these classes over arrays is that they can grow and shrink as the number of
stored objects changes.
The List <T> class is contained with the System.Collections.Generic namespaces
while the ArrayList class is contained within the System.Collections namespace.
The syntax for creating a List <T> Collection is as follows.
List <type> name = new List <type> ();
An ArrayList object is created in a similar manner, although without the type argument.
ArrayList name = new ArrayList ();
With the above syntax in mind we can now create a List <T> object called ColorList.Using
System;
Using System.Collections.Generic;

Public class Lists


{
Static void Main ()
{
List <string>colorlist = new List <string> ();
}}
Adding Items to Items:
Once a List object has been created there are a number of methods which may be called to
perform tasks on the List. One such method is the Add () method which, as the name suggests,
isused to add items to the List Object.
List <String>colorlist = new List
<string> ();colorlist.Add (―Red‖);

U20CSCM02-C# AND .NET PROGRAMMING 41


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

colorlist.Add(―Green‖);
colorlist.Add(―Yellow‖);
colorlist.Add(―Purple‖);
colorlist.Add(―Orange‖);
Accessing List Items:
Individual items in a list may be accessed using the index value of the item (keeping in mind
thatthe first item is index 0, the second index 1 and so on). The index value is placedin square
brackets after the list name. For example, to access the second item in the colorlist object.

Console.WriteLine (colorlist[1]);
A list item value can similarly be changed using the index combined with theassignmentoperator.
For example, to change the color from Yellow to Indigo,
Colorlist [2] =‖Indigo‖;
All the items in a list may be accesses using a foreach loop. For
example:foreach (string color in colorlist)
{
Console.WriteLine (color);
}
When compiled and executed, the above code will output each of the color strings inthe
colorstrings in the colorlist objects:
Colorlist.Remove (―red‖);
It is important to note that items in a List may be duplicated. In the case of duplicated items,
theRemove () method will only Remove the first matching instances.
Inserting Items into a C# List:
Previously we used the Add () method to add items to a list. The add () method, however, only
adds items to the end of a list. Sometimes it is necessary to insert a newitem at a specific
location in a list. The Insert () method is provided for this specific purpose. Insert () takes two
arguments, an integer indicating the index location of the insertion and the index location of
theinsertion and the item to be inserted at that location 2 in our example list.
Colorlist.Insert (2,
―white‖); Sorting Lists in
C#:
There is no way to tell C# to automatically sort a list as items are added. If the items in a list
arerequired to be always sorted into order the sort () method should be called afternew times
are added.

U20CSCM02-C# AND .NET PROGRAMMING 42


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Colorlist.Sort ();
Finding Items in a C# List or ArrayList
A number of methods are provided with the List and ArrayList classes for the purpose of
finding items. The most basic method is the contains () method, which when called on a List or
ArrayList object returns true if the specified item is found in the list, or false if it is
not.Theindexof () method returns the index value of a matching item in a List. For example, the
following code sample will output the value 2, which is the index position of the ―Yellow‖
string.
List <string>colorlist = new List
<string> ();colorlist.Add(―Red‖);
colorlist.Add(―Green‖);
colorlist.Add(―Yellow‖);
colorlist.Add(―Purple‖);
colorlist.Add(―Orange‖);
Console.WriteLine (colorlist.Indexof (―Yellow‖));
If the item is not found in the List a value of -1 is returned by the Indexof () method.
Thistechnique could be used to replace a specific value with another. For example, withoutknowing
in advance the index value of the ―Yellow‖ string we can change to ―Black‖.
Colorlist [colorlist.Indexof(―Yellow‖)] = ―Black‖;
The LastIndexof () method returns the index value of the last item in the list tomatch
the specified item. This is particularly useful when a list contains duplicate items. Obtaining
Information About a List:
 There are two class members that are useful for obtaining information about a C# List or
ArrayList collections object. The capacity property can be used to identify how many
items a collection can store without having to resize.
 The count property, on the other hand, identifies how many items are currently stored in
the list. Capacity will always exceed count.
 In instance where a large gap exists between count and capacity the excess capacitymay be
removed with a call the TrimExcess () method.
Clearing and Triming C# Lists:
All the items in a list may be removed using the clear ()
method.Colorlist.Clear ();
The Clear () method removes the items from the list and sets the Count property to zero.

U20CSCM02-C# AND .NET PROGRAMMING 43


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

The capacity property, however, remains unchanged. To remove the capacity of a list follow the
Clear () method call with a call to TrimExcess ().
7.Explain Exception Handling In Detail. (Nov2013) (Nov 2012) (Apr’14)
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
exceptionsare anomalies that occur during the execution of a program. They can be
because of user, logic or system errors. If a user does not provide a mechanism to handle
these anomalies, the .NET run time environment provides a default mechanism, which
terminates the program execution.
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 general form try – catch finally in C# is shown below.

Try
{
//statements which 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.
But in C#, both catch and finally blocks are optional. The try block can exist either with
one or more catch blocks as a finally block or with catch and finally blocks.
If there is no exception occurred inside the try block, the control directly transfers to
finally block. We can say that the statements inside the finally block is executed always.
Note that it is an error to transfer control out of a finally block by using break, continue,
return or goto.

U20CSCM02-C# AND .NET PROGRAMMING 44


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

In a C#, exceptions are nothing but objects of the type exception. The Exception is the
ultimate Base class for any exceptions in C#.
The C# itself provides couple of standard exceptions. Or even Exception class or one of
the standard derived classes of exception class like DivideByZeroException and
ArgumentException etc.

Example for Exception Handling:


Using System;

Class Myclient;
{
Public static void Main ()
{
int x=0; int div =0;try
{
Div =100/x;
Console.Writeline (“Not executed Line”);
}
Catch (DivideByZeroException de)
{
Console.Writeline (“Exception Occurred”);
}
Finally
{
Console.WriteLine (“Finally Block”);
}
Console.WriteLine (“Result is {0}”, div);
}}
In C#, a try block must be followed by either a catch orfinally
block.

Multiple Catch Block:


A try can throw multiple exceptions, which can handle by using multiple catch
blocks.We must remember that more specialized catch block should come before a
generalized one.

U20CSCM02-C# AND .NET PROGRAMMING 45


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Using System;Class
Myclient
{
Public static void Main ()
{
int x=0; int div =0;try
{
div =100/x;
Console.WriteLine (“Not Executed Line”);
}
Catch (DivideByZeroException de)
{
Console.Writeline (“DivideByZeroException”);
}
Catch (Exception ee)
{
Console.WriteLine (“Exception”);
}
Finally
{
Console.WriteLine (“Finally Block”);
}
Console.WriteLine (“Result is {0}”, div);
}}
Standard Exceptions:

1. There are two types of exceptions: exceptions generated by an executing program and
exceptions generated by the common language RunTime.System.Exception is the base class for
all exceptions in C#. Several exception classes inherit from this class including
ApplicationException and SystemException. These two classes from the basis for most other
runtime exceptions. Other exceptions that derive directly from System.Exception include
IOException, WebException etc

2. The common language Runtime throws SystemException. The ApplicationException is thrown


by a user program rather than the runtime. The SystemException includes the
ExecutionEngineException, StackOverflowException etc. It is not recommended that we catch
system Exceptions nor is it good programming practice to throw System Exceptionsin our
applications.

U20CSCM02-C# AND .NET PROGRAMMING 46


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

- System.OutofMemory Exception

-System.NullReference Exception
-System.InvalidCast Exception
-System.ArrayTypeMismatch Exception
-System.IndexOutofRange Exception

-System.Arithmetic Exception
-System.DivideByZero Exception
-System.Overflow Exception

User – defined Exceptions:

In C#, it is possible to create our own exception class; But Exception must be the
ultimatebase class for all exceptions in C#. So the user – defined exception classes must inherit
from either Exception class or one of its standard derived classes.
Example:
Using System;
Class MyException: Exception
{
Public MyException (string str)
{
Console.WriteLine (―User Defined Exception‖);
}}
Class Myclient
{
Public static void Main ()
{
Try
{
Throw new MyException (“ROSE”);
}
Catch (Exception e)
{
Console.WriteLine (“Exception caught here” + e.ToString ());

U20CSCM02-C# AND .NET PROGRAMMING 47


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

}
Console.WriteLine (“Last Statement”);
}}

8. Explain multithreading in C#: (MAY-22)

A thread is defined as the execution path of a program. Each thread defines a unique flow of
control. If your application involves complicated and time consuming operations, then itis often
helpful to set different execution paths or threads, with each thread performing a particular job.
Threads are lightweight processes. One common example of use of thread is implementation of
concurrent programming by modern operating systems. Use of threadssaves wastage of CPU
cycle and increase efficiency of an application.
So far we wrote the programs where a single thread runs as a single process which is the running
instance of the application. However, this way the application can perform one jobat a time. To
make it execute more than one task at a time, it could be divided into smaller threads.

Thread Life Cycle


The life cycle of a thread starts when an object of the System.Threading.Thread class is createdand ends
when the thread is terminated or completes execution.
Following are the various states in the life cycle of a thread −
 The Unstarted State − It is the situation when the instance of the thread is created but the
Start method is not called.
 The Ready State − It is the situation when the thread is ready to run and waiting CPUcycle.
 The Not Runnable State − A thread is not executable, when
o Sleep method has been called
o Wait method has been called
oBlocked by I/O operations
 The Dead State − It is the situation when the thread completes execution or is aborted.
The Main Thread
In C#, the System.Threading.Thread class is used for working with threads. It allows creating and
accessing individual threads in a multithreaded application. The first thread to be executed in a process
is called the main thread.
When a C# program starts execution, the main thread is automatically created. The threads created
using the Thread class are called the child threads of the main thread. You can access a thread using
the CurrentThread property of the Thread class.
The following program demonstrates main thread execution –

using System;
using System.Threading;

namespace MultithreadingApplication {

U20CSCM02-C# AND .NET PROGRAMMING 48


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

class MainThreadProgram {
static void Main(string[] args) {
Thread th = Thread.CurrentThread;
th.Name = "MainThread";

Console.WriteLine("This is {0}", th.Name);


Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result –
This is MainThread.
Creating Threads
Threads are created by extending the Thread class. The extended Thread class then callsthe
Start() method to begin the child thread execution.
The following program demonstrates the concept –

using System;
using System.Threading;

namespace MultithreadingApplication {
class ThreadCreationProgram {
public static void CallToChildThread() {
Console.WriteLine("Child thread starts");
}
static void Main(string[] args) {
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result –
In Main: Creating the Child threadChild
thread starts
Managing Threads
The Thread class provides various methods for managing threads.
The following example demonstrates the use of the sleep() method for making a thread pausefor a
specific period of time.

using System;
using System.Threading;

namespace MultithreadingApplication {

U20CSCM02-C# AND .NET PROGRAMMING 49


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

class ThreadCreationProgram {
public static void CallToChildThread() {
Console.WriteLine("Child thread starts");

// the thread is paused for 5000 milliseconds


int sleepfor = 5000;

Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000);


Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}

static void Main(string[] args) {


ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");

Thread childThread = new Thread(childref);


childThread.Start();
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
In Main: Creating the Child threadChild
thread starts
Child Thread Paused for 5 seconds
Child thread resumes
Destroying Threads
The Abort() method is used for destroying threads.
The runtime aborts the thread by throwing a ThreadAbortException. This exception cannotbe
caught, the control is sent to the finally block, if any.
The following program illustrates this −

using System;
using System.Threading;

namespace MultithreadingApplication {
class ThreadCreationProgram {
public static void CallToChildThread() {
try {
Console.WriteLine("Child thread starts");

// do some work, like counting to 10


for (int counter = 0; counter <= 10; counter++) {
Thread.Sleep(500);
Console.WriteLine(counter);
}

U20CSCM02-C# AND .NET PROGRAMMING 50


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

Console.WriteLine("Child Thread Completed");


} catch (ThreadAbortException e) {
Console.WriteLine("Thread Abort Exception");
} finally {
Console.WriteLine("Couldn't catch the Thread Exception");
}
}
static void Main(string[] args) {
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");

Thread childThread = new Thread(childref);


childThread.Start();

//stop the main thread for some time


Thread.Sleep(2000);

//now abort the child


Console.WriteLine("In Main: Aborting the Child thread");

childThread.Abort();
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
In Main: Creating the Child threadChild
thread starts
0
1
2
In Main: Aborting the Child threadThread
Abort Exception
Couldn't catch the Thread Exception

9. Write a C# program for overloading binary operator


(Nov’14)Binary operator overloading:
Using System;
Namespace binary_overload
{
Class complexNumber{
int x;
double y;
publiccomplexNumber(int real, double imagnary)

U20CSCM02-C# AND .NET PROGRAMMING 51


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

{
x = real;
y = imagnary;
}
publiccomplexNumber()
{
public static complexNumber operator + (complexNumber c1, complexNumber c2)
{
complexNumber c = new
complexNumber();c.x=c1.x+c2.x;
c.y=c
1.x-
c2.y;
return
c;
}
public void show()
{
Console.Write(x);
Console.Write("+j
"+y);
Console.WriteLine();
}
}
class Program
{
static void Main(string[] args)
{
complexNumber p, q, r;
p = new complexNumber(10, 2.0);q =
new complexNumber(20, 15.5);

U20CSCM02-C# AND .NET PROGRAMMING 52


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE Dept of CSE

r = p + q;
Console.Write("p=
");
p.show();
Console.Write("q=
");
q.show();
Console.Write("r=
");
r.show();
Console.ReadLine();
}
}
}

Note:-
The Method operator + () takes two argument (ComplexNumber) and add the two objects in
same class.

U20CSCM02-C# AND .NET PROGRAMMING 53

You might also like