C# Unit - III
C# Unit - III
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;
}
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);
}
}
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
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
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:
}
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:
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.
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
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.
class Maruthi
{
public virtual void Display()
{
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)
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:
Animal
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
Example:
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,
}
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 ();
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 ()
{
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
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.
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 duplicateditems,
theRemove () method will only Remove the first matching instances
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
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);
}}
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.
}
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 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
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;
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;
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 {
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.
The derived class inherits the fields and methods of the base class. This helps with the code
reusability in C#.
Example:
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 {
}}
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
Hierarchical
Inheritance
Example:
Animal
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.
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
Using System;
Class Square
{
Public double x;
Public Square (double x)
{
this.x = x;
}
OUTPUT:
Area of Square
= 27.04Area of
Cube = 162.24
OVERLOADING VS OVERRIDING
Using system.Ling;
Using system.Text;
Namespace console application 6
{
Using system;
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.
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.
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.
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.
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.
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.
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
- System.OutofMemory Exception
-System.NullReference Exception
-System.InvalidCast Exception
-System.ArrayTypeMismatch Exception
-System.IndexOutofRange Exception
-System.Arithmetic Exception
-System.DivideByZero Exception
-System.Overflow Exception
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 ());
}
Console.WriteLine (“Last Statement”);
}}
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.
using System;
using System.Threading;
namespace MultithreadingApplication {
class MainThreadProgram {
static void Main(string[] args) {
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
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 {
class ThreadCreationProgram {
public static void CallToChildThread() {
Console.WriteLine("Child thread starts");
using System;
using System.Threading;
namespace MultithreadingApplication {
class ThreadCreationProgram {
public static void CallToChildThread() {
try {
Console.WriteLine("Child thread starts");
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
{
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);
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.