0% found this document useful (0 votes)
12 views

Unit 3-1

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)
12 views

Unit 3-1

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

Unit 3

Exception& object life time and interface and collections


Classes, Objects, and References
➢ class is a blueprint that describes how an instance of this type will look and
feel in memory
➢ Once a class is defined, we can create any number of objects using the C# new
keyword.
➢ The new keyword returns a reference to the object in the memory.
➢ This reference variable is stored on the stack for further use.
➢ After creating objects, we can use members of the class using object name and
dot operator.

The Basics of Object Lifetime


The rule of .NET memory management is simple:
Rule 1:
➢ Allocate an object onto the managed heap using the new keyword.
➢ After the object is created using new keyword, the garbage collector will
destroy the object when it is no longer needed.
➢ The garbage collector removes the object from the Heap when it is
unreachable by any part of your code base.
Public static void MakeACar()
{
Car myCar = new Car();
...
}

Vasudha GS, SRNMNC, Shimoga Page 1


Here, the object of class car (myCar) has been created directly within the
MakeACar() by using new keyword and will be destroyed by the garbage collector
when the function completes its execution.
The CIL of new operator:
➢ When the C# compiler encounters the new keyword, it will emit a CIL
newobj instruction into the method implementation.
➢ The .NET garbage collector is housekeeper of the heap, given that it will
compact empty blocks of memory (when necessary) for purposes of
optimization.
➢ The managed heap maintains a pointer (commonly referred to as the next
object pointer or new object pointer) that identifies exactly where the next
object will be located.
➢ newobj instruction informs the CLR to perform the following core tasks:
▪ Calculate the total amount of memory required for the object to
be allocated.
▪ Examine the managed heap to ensure that there is enough space
▪ To host the object to be allocated.
▪ If this is the case, the type’s constructor is called, and it returns
reference to the new object in memory
▪ Finally, before returning the reference to the caller, increment the
next object pointer to point to the next available slot on the
managed heap.
➢ As the objects are allocated, the space on the managed heap may become full.
When processing the newobj instruction, if the CLR determines that the
managed heap does not have sufficient memory to allocate the requested type,
it will perform a garbage collection attempt to free up memory. Thus, the next
rule of garbage collection is also simple.
Vasudha GS, SRNMNC, Shimoga Page 2
Rule 2:
➢ If the managed heap does not have sufficient memory to allocate a requested
object,a garbage collection will occur.
➢ When a collection does take place, the garbage collector temporarily suspends
all active threads within the current process to ensure that the application does
not access the heap during the collection process.
➢ A thread is a path of execution within a running executable. Once the garbage
collection cycle has completed, the suspended threads are permitted to carry
on their work.
The Role of Application Roots
➢ A root is a storage location containing a reference to an object on the heap
➢ A root can be of any of the following types:
1. References to global objects.
2. References to currently used static objects/static fields .
3. References to local objects within a given method
4. References to object parameters passed into a method.
5. References to objects waiting to be finalized .
6. Any CPU register that references a local object.
➢ During a garbage collection process, the runtime will check objects on the
managed heap to determine if they are still reachable by the application.
➢ To do so, the CLR will build an object graph, which represents each
reachable object on the heap.
➢ The following diagram shows sample object graph used to determine which
objects are reachable by application roots.

Vasudha GS, SRNMNC, Shimoga Page 3


➢ Object graphs are used to document all reachable objects. The garbage
collectors will never graph the same object twice.
➢ Here assume that the managed heap contains a set of objects names
A,B,C,D,E,F and G. During garbage collections these objects are examined
for active roots.
➢ One the graph has been constructed, unreachable objects are marked as
gabage.( In the diagram C and F are considered as garbage).
➢ Once an object ahs been marked for termination, they are swept from
memory.
➢ At this point the remaining space on the heap is compacted and the next object
poionter is readjusted to point to the next available slot as shown below:

Understanding Object Generations

Vasudha GS, SRNMNC, Shimoga Page 4


➢ When the CLR is trying to find unreachable objects, it does not examine each
and every object placed on the managed heap because it would involve
considerable time for larger applications.
➢ To help optimize the process, each object on the heap is assigned to a specific
“generation.”
➢ The idea behind generations is simple: The longer an object has existed on the
heap, the more likely it is to stay there.
➢ Each object on the heap belongs to one of the following generations:
1.Generation 0: Identifies a newly allocated object that has never been
marked for collection
2.Generation 1: Identifies an object that has survived a garbage collection .
3.Generation 2: Identifies an object that has survived more than one sweep
of the garbage bcollector
Forcing a Garbage Collection
➢ The purpose of the .NET garbage collector is to manage memory.
➢ Sometimes it is necessary to programmatically force a garbage collection
using GC.Collect(). Specifically:
1. If the application is entering a block of code that should not be interrupted
by a possible garbage collection.
2. Your application has just finished allocating an extremely large number
of objects and you wish to remove as much of the acquired memory as
possible.
3. If you determine it may be beneficial to have the garbage collector check
For unreachable objects, you could explicitly trigger a garbage collection, as
follows:
static void Main(string[] args)
{
Vasudha GS, SRNMNC, Shimoga Page 5
...
GC.Collect();
GC.WaitForPendingFinalizers();
...
}
➢ When you manually force a garbage collection, you should always make a
call to GC.WaitFor-PendingFinalizers().

The System.GC Type:


➢ The base class libraries provide a class type named System.GC that allows
you to programmatically interact with the garbage collector using a set of
static members.
➢ The following table shows some of the members of the System.GC Type:
Sl. System.GC Memebr Meaning
No
1 AddMemoryPressure() Allows you to specify a numerical value
RemoveMemoryPressure() that represents the calling object’s
“urgency level” regarding the garbage
collection process.
2 Collect() Forces the GC to perform a garbage
collection
3 CollectionCount() Returns a numerical value representing
how many times a given generations has
been swept.
4 GetGeneration() Returns the generation to which an object
currently belongs.

Vasudha GS, SRNMNC, Shimoga Page 6


5. GetTotal Memory() Returns the estimated amount of memory
(in bytes) currently allocted on the
managed heap.
6. MaxGeneration() Returns the maximum of generations
supported on the target system.
7 SupressFinalize() Sets a flag indicating the specified object
should not have its Finalize() method
mcalled.
8. WiatForPendingFinalizers() Suspends the current thread until all
finalizable objects have been finalized.
This method is typically called directly
after invoking GC.Collect()

The following program illustrates the use of members of the System.GC class:
class Demo
{
public static void main(String [] args)
{
Consloe. writeLine(“Estimaetd bytes on Heap:{0}”, GC.GetTotalMenory(false));
Consloe. WriteLine(“This OS has {0} object generations”,
(GC.MaxGeneration+1));
Car c=new Car();
Consloe. WriteLine(c.ToString());
Console.WriteLine(“Generation of c is :{0}”,GC.GetGenearation©);
Consloe.readLine();
}

Vasudha GS, SRNMNC, Shimoga Page 7


}
Exception handling:
Errors, Bugs and Exceptions:
Bugs: This is an error on the part of the programmer.
User Errors: User errors are typically caused by the individual; running yopur
application , rather than by those who created it.
Exceptions: Exceptions are typically regarded as runtime anomalies that are
difficult , if not impossible to account for while programming your application.
Types of errors:
Errors can be classified into two types:
1. Compile time errors
2. Run time errors.
All syntax errors that are detected and displayed by the c# compiler are called
compile time errors. The common compile time errors are : missing semicolon,
missing brackets, missing of identifiers, keywords, missing double quotes, use of
undeclared variables, bad reference to objects etc.
Sometime, a program may compile successfully but may not run properly due
to wrong logic or terminate due to errors such as stack overflow. Such errors are
called as run time errors. The common runtime errors are: division by zero, accessing
an element that is out of the bounds of an array, trying to store a value into an
incompatible class or type, attempting to use a negative size for an array etc.

Exception:
➢ An exception is a condition that is caused by the runtime error in the program.

Vasudha GS, SRNMNC, Shimoga Page 8


➢ When a c# compiler encounters an error, it creates an exception object and
throws it.
➢ If the exception object is not caught and handled properly, the comiler will
display an error message and terminate the program.’
➢ If we want to continue the execution of program, then the exception object
must be caught and appropriate message should be displayed. This process of
catching object thrown by the exception and displaying appropriate error
message is called as exception handling.
➢ The purpose of exception handling is to provide a mechanism is to provide a
means to detect and report exceptions.
➢ The exception handling code performs the following task:
1. Find the problem(Hit the exception)
2. Inform that an error has occuredThrow the exception)
3. Receive the error information(Catch the exception)
4. Take corrective actions(handle the exception)
➢ The common error handling code includes two segments: one for detecting
errors and to throw exceptions, another one to catch exceptions and take
appropriate actions.
The Role of .Net Exception Handling:
➢ The .Net platform provides a standard technique to send and trap runtime
errors: Structured Exception Handling.
➢ This approach helps the developers to have a unified approach to error
handling which is common to all languages targeting the >net universe.
➢ The syntax used to throw and catch exceptions across the assemblies and
machines are identical.
➢ Another advantage of .Net exceptions is that instead of receiving cryptic
numerical value that identifies the problem and provides human readable
Vasudha GS, SRNMNC, Shimoga Page 9
description of the problem as well as detailed snapshot of the call stack that
triggered the exception.
➢ The following table shows common c# exceptions:
Exception class Cause of exception
Systemexception This is used as a base for other
exceptions
AccesssException Failure to access a type member
Argumnetexception An invalid argument to the method
ArgumentNullexception A null argument was passed to a
method that does not accept it
argumentOutofRangeexception Argument value is out of range
Arithmetic exception Arithmetic overflow or underflow
DivideByZeroException An attempt to divide by zero
FormatException The format of an argument is
wrong
IndexOutOfrange An array index is out of bounds
StackOverflowException A stack has overflowed

Syntax of exception handling code:


➢ The basic concepts of exception handling is throwing and catching
exceptions as shown below:

Vasudha GS, SRNMNC, Shimoga Page 10


Try block

Statements that
causes exception

Throws
Exception
Catch block
Object
Statements that
handles the exception

➢ C# uses a keyword try to define a block of code that is likely to cause


an error condition and throws an exception.
➢ A catch block is defined by the keyword Catch, that catches an
exception thrown by the try block and handles it appropriately.
➢ The syntax of simple try catch block is as follows:
Try
{
Statements;
}
Catch(Exception e).
{
Statements;
}
➢ The try block can have one or more statements that could generate an
exception. If any statement generates an exception, the remaining
statements in the block are skipped and execution jumps to the catch block
that is placed immediately after try block.
Vasudha GS, SRNMNC, Shimoga Page 11
➢ The catch block can have one or more statements to process the exception
thrown by the try block.
➢ The catch block is passed a single parameter, if the catch parameter
matches with the type of exception object, then the exception is caught
and statements in catch block will be executed.
Example: program to demonstrate simple try catch block:
Using system;
Class eg
{
Public static void Main()
{
Int a=10;
Int b=5;
Int c=5;
Int x,y;
Try
{
X=a/(b-c)
}
Catch(Exception e)
{
Console.WriteLine(“division by zero”);
}
Y=a/(b+c);
Console.WriteLine(“y=”,+y);
}

Vasudha GS, SRNMNC, Shimoga Page 12


Multiple catch statements:
➢ It is possible to have more than one catch statements in the catch block.
➢ The syntax for multiple catch block is as follows:
Try
{
Statement;
}
Catch (Exception-type -1 e)
{
Statement;
}
Catch (Exception-type2 e)
{
Statement;
}
…….
……..
……..
Catch (Exception-typeN e)
{
Statement;
}
➢ When an exception in a try block is generated. the c# treats the multiple catch
statements like cases in switch statement.
➢ The first statement whose parameter matches with the exception object will
be executed; the remaining statement will be skipped.
Example: program to demonstrate multiple catch blocks:
Vasudha GS, SRNMNC, Shimoga Page 13
Using System;
Class Eg4
{
Public static void main ()
{
Int a[]={5,10};
Int b=5;
Try
{
Int x=a[2]/b-a[1];
}
Catch(Arithmeticexception e)
{
Console.writeLine(“division by zero”);
}
Catch(IndexOutOfRangeexception e)
{
Console.writeLine(“array index error”);
}
Catch(ArrayTypeMismatchexception e)
{
Console.writeLine(“wrong data type”);
}
Int y=a[1]/a[0];
Console.writeLine(“y= “y);
}
}
Vasudha GS, SRNMNC, Shimoga Page 14
Exception hierarchy:
➢ All c# Exceptions are derived from the class exception.
➢ When an exception occurs, the proper catch handler is determined by
matching the type of exception to the name of exception mentioned.
➢ If we are going to catch exceptions at different levels in the hierarchy, we
need to put them in the right order.
➢ The rule is that we must always put the handlers for the most derived class
first.

General catch handler:


➢ A catch block which will catch any exception is called a general catch
handler.
➢ A general catch handler does not specify any parameter and can be written as:
Try
{
…….
………..
}
Catch
{
…………
……………
}

➢ Catch(Exception e) can handle all the exceptions thrown by c# code and


therefore can be used as a general catch handler.
Vasudha GS, SRNMNC, Shimoga Page 15
➢ If the program uses libraries written in other languages, then exception
generated by such code will be handled by the parameter-less catch block.
➢ This type of catch block is always placed at the end.
Finally statement:
➢ C# supports another statement known as finally which can be used to handle
exceptions that is not caught by any catch statements.
➢ A finally block can be used to handle any exception generated within a try
block.
➢ It may be added immediately after the try block or it may be added after the
last catch block as shown below:
Try Try
{ {
………….. …………..
………….. …………..
} }
Finally Catch(…….)
{ {
………….. …………..
…………… ……………
} }
Catch(…….)
{
…………..
……………
}
.

Vasudha GS, SRNMNC, Shimoga Page 16


.
.
Finally
{
……………..
…………….
}

➢ When a finally block is defined, the program is guaranteed to execute,


regardless of how control leaves the try, whether it is due to normal
termination ,due to an exception or due to jump statement.
Nested Try blocks:
➢ C# permits us to use nested try blocks inside each other as follows:
Try
{
……(point p1)
………..
Try
{
……….((point p2)
……………
}
Catch
{
…..(point p3)
……….
}
Vasudha GS, SRNMNC, Shimoga Page 17
Finally
{
……….
3……….
}
…………..(point 4)
………………..
}
Catch
{
………..
}
Finally
{
………
}
➢ The point p1 and p2 are outside the inner try block and therefore any
exceptions thrown at these points will be handled by the catch in the outer
block.
➢ Any exceptions thrown at point p2 will be handled by the inner catch handler
and the inner finally will be executed.
➢ If there is no suitable catch handler to catch an exception thrown at p2, the
control will leave the inner block and look for suitable catch handler in the
outer block.

Throwing our own exception:


➢ There may be times when we would like to throw our own exceptions.
Vasudha GS, SRNMNC, Shimoga Page 18
➢ We can do this by using the keyword throw as follows:
Throw new throwableexception;
Examples:
Throw new ArithmeticException();
Throw new FormatException();
Example:Program to demonstrate throwing our own exception:
Using system;
Class MyException:Exception
{
Public MyException(String Message):base(Message)
{
}
Public MyException(string Message,Exception inner):base (Message,inner)
{
}
}
Class TestMyException
{
Public static void Main()
{
Int x=5, y=1000;
Try
{
Float z=(float)x/(float)y;
If(z<0.01)
{
Throw new MyException(“number is too small”);
Vasudha GS, SRNMNC, Shimoga Page 19
}
}
Catch(MyException e)
{
Console.WriteLine(“caught my exception”);
Console. writeLine(e.Message);
}
Finally
{
Console.WriteLine(“I am always here”);
}
}
}
}
The object e which contains the error message “number is too small” is caught by
the catch block which then displays the message using message property.
Throwing a generic Exception:
Generic exceptions can be thrown by creating an object of the Exception class
using new operator and constructor of the Exception class with message to be
displayed when the exception occurs. This is illustrated in the following example:
Program:
Class sample
{
public static void main(String [] args)
{
Int x=5, y=1000;
Try
Vasudha GS, SRNMNC, Shimoga Page 20
{
Float z=(float)x/(float)y;
If(z<0.01)
{
Throw new Exception(“number is too small”);
}
}
Catch(Exception e)
{
Console. writeLine(“Message:{0}”,e.Message);
}

}
System. Exception Type:
The following table shows core members of the System.Exception Type:
Sl.No System. Meaning
Exception.Property
1 Data This property retrieves a collection of Key/value
pairs that provide additional user-defined
information about the exception .
2 HelpLink This property returns a URL to help a file
describing the error in full detail.
3 InnerException This read only property can be used to obtain
information about the previous exceptions that
caused the exception to occur.

Vasudha GS, SRNMNC, Shimoga Page 21


4. Message This read only property returns the textual
description of a given error.
5. Source This property returns the textual description of a
given error. The message itself is set as a
constructor parameter.
6. Stack Trace This read-only property contains a string that
identifies the sequence of the calls that triggered
the exception.
7 Target Site This read –only property returns a MethodBase
type, which describes numerous details about the
method that threw the exception.

1. The TargetSite Property:


The TargetSite property allows you to determine the various details about the
method that threw a given exception. Printing the value of TargetSite display the
return value, name and parameters of the method that threw the exception. This
property can be used to gather numerous details regarding the exception. The
following example illustrates the usage of targetSite Property.
Program:
Class sample
{
public static void main(String [] args)
{
Int x=5, y=1000;
Try
{
Float z=(float)x/(float)y;
Vasudha GS, SRNMNC, Shimoga Page 22
If(z<0.01)
{
Throw new Exception(“number is too small”);
}
}
Catch(Exception e)
{
Console. writeLine(“Member Name: {0}”,e.TargetSit0065);
Console. writeLine(“Member Type: {0}”,e.TargetSite.MemberType);
Console. writeLine(“Message:{0}”,e.Message);
}
}
2. The StackTrace Property:
The StackTrace property allows you to identify the series of calls that resulted
in the exception. The value of StackTrace is automatically established automatically
at the time the exception is created. The StackTrace documents the sequene of calls
that resulted in throwing the exception. The following code illustrates the StackTrace
property:
Class sample
{
public static void main(String [] args)
{
Int x=5, y=1000;
Try
{
Float z=(float)x/(float)y;
If(z<0.01)
Vasudha GS, SRNMNC, Shimoga Page 23
{
Throw new Exception(“number is too small”);
}
}
Catch(Exception e)
{
Console. writeLine(“Stack:{0}”,e.StackTrace);
Console. writeLine(“Message:{0}”,e.Message);
}
}
3. The Help Link property:
The HelpLink property is used to set to point the user to a specific URL or
standard Windows help file that contains the detailed information.
Program:
Class sample
{
public static void main(String [] args)
{
Int x=5, y=1000;
Try
{
Float z=(float)x/(float)y;
If(z<0.01)
{
Exceptoion ex=new Exception(number is too small” );
ex.HelpLink=http://www.errors.com;
Throw ex;
Vasudha GS, SRNMNC, Shimoga Page 24
}

}
Catch(Exception e)
{
Console. writeLine(“HelpLink{0}”,e.HelpLink);
}
}
4. The Data Property:
The DataProperty of Ssyem. Exception allows us to fill an excpetion object
with the releavent user supplied information. The data property returns an object
implementing an interface named IDictionary, defined in the System.Coolection
namespace.
Example :
Class sample
{
public static void main(String [] args)
{
Int x=5, y=1000;
Try
{
Float z=(float)x/(float)y;
If(z<0.01)
{
Exceptoion ex=new Exception(number is too small” );
ex.HelpLink=http://www.errors.com;
ex.Data.Add(“ The Number is too small. Please Enter a value which is
Vasudha GS, SRNMNC, Shimoga Page 25
greater than one. “);
Throw ex;
}

}
Catch(Exception e)
{
Console. writeLine(“HelpLink{0}”,e.HelpLink);
}
}

Checked and unchecked operators:


Stack overflows are usual problems during arithmetic operations and conversion of
integer types. C# supports two operators: Checked and unchecked. These two
operators can be used for checking and unchecking stack overflows during program
execution. If an operation is checked, then an exception will be thrown if overflow
occurs. If it is not checked, no exception will be thrown and we will lose the data.
Int a=200000;
Int b=300000
Try
{
Int m=checked(a*b);
}
Catch(overflowexception e)
{
Console.WriteLine(e);
Vasudha GS, SRNMNC, Shimoga Page 26
}
Since a*b produces a value that will be easily exceed the maximum value for an int,
an overflow occurs. As the operation is checked with operator Checked, an overflow
exception will be thrown.

Interface: Multiple Inheritances


Interface:
➢ C# does not support multiple inheritances directly, but to implement multiple
inheritances it provides a concept called as Interface.
➢ An interface in C# is a reference type. It is basically a kind of class with some
differences. They are:
1. All the members of an interface are implicitly public and abstract
2. An interface cannot contain constant fields, constructors, destructors.
3. Its members cannot be declared as static
4. The methods in interface will not have implementation.
5. An interface can inherit multiple interfaces.
Thus we can define an interface as a reference type which contains only public and
abstract members and methods without any implementation code.
Defining an Interface:
➢ An interface can contain one or more methods, properties, indexers and events
but none of them are implemented in the interface.
➢ It is the responsibility of class that implements the interface to define the
implementation of these members.
➢ The syntax of interface definition is as follows:
Interface interfaceName
{
Member declaration;
Vasudha GS, SRNMNC, Shimoga Page 27
}
➢ Here, interface is the keyword, and interface name is any valid C# identifier.
Member declaration will contain only a list of members without
implementation code.

Example:
Interface show
{
Void display();
}
Here, interface show is defined with a member display().

Extending an interface:
➢ Like classes, interfaces can also be extended.
➢ The interface can be subinterfaced from other interfaces. The new sub
interface will inherit all the members of the super interface in the manner
similar to subclasses.
➢ The syntax is as follows:
Interface name2:name 1
{
Members of name2;
}
Example:
Interface addition
{
Int add(int x, int y);
}
Vasudha GS, SRNMNC, Shimoga Page 28
Interface compute:addition
{
Int sub(int x, int y);
}
The interface compute will have both the methods and any class implementing
the interface compute should implement both of them.
➢ We can combine several interfaces together into a single interface.
➢ While interfaces are allowed to extend other interfaces, subinterfaces can not
define the method declared in the superinterface.
➢ It is the responsibility of class that implements the derived interface to define
all the methods.
➢ Interfaces can not extend classes.

Implementing interfaces:
➢ Interfaces acts as superclasses whose properties are inherited by classes.
➢ It is therefore necessary to create a class that inherits the given interfaces.This
is done as follows:
Class classname: interfacename
{
Body of classname;
}
Here, the class classname implements the interface interfaceName. A more
general form of implementation may look like this:
Class classname: Super class, interface1, interface2……
{
Body of classname;
}
Vasudha GS, SRNMNC, Shimoga Page 29
This shows that a class can extend another class while implementing
interfaces.
Example: program to implement multiple interfaces
Using system;
Interface Adddition
{
Int add();
}
Interface multiplication
{
Int mul();
}
Class computation:addition,multiplication
{
int x,y;
Public computation(int x, int y)
{
This.x=x;
This. Y=y;
}
Public int add()
{
return(x+y);
}
Public int mul()
{
Return(x*y);
Vasudha GS, SRNMNC, Shimoga Page 30
}
}
Class interfacetest1
{
Public static void main()
{
Computation com= new computation (10,20);
Addition add=(addition)com;
Console. writeLine(“sum=”+add.Add());
Multiplication mul=(Multiplication)com;
Console. writeLine(“product=”+mul.Mul());
}
}

Example: program to demonstrate multiple implementations of interfaces:


Using System;
Interface area
{
Double compute(double x);
}
Class square:Area
{
Public double compute(double x)
{
Return(x);
}
}
Vasudha GS, SRNMNC, Shimoga Page 31
Class circle:area
{
Public double compute(double x)
{
Return(Math.PI*X*X);
}
}
Class interfaceTest2
{
Public static void main()
{
Square sqr=new Square();
Circle cir =new circle();
Area area;
Area=sqr as Area;
Console. WriteLine(“area of square=”+area.compute(10.0));
Area=cir as Area;
Console.WriteLine(“Area of circle=”+area.compute(10.0));
}
}
Interfaces and inheritance:
➢ Sometimes where the base class of a derived class of implements an interface.
➢ In such situations, when an object of the derived class is converted to the
interface type, the inheritance hierarchy is searched until it finds a class that
directly implements the interface.
Example: Program to demonstrate inheriting a class that implements an
interface:
Vasudha GS, SRNMNC, Shimoga Page 32
Using system;
Interface Display
{
Void paint();

}
Class B:Display
{
Public void print()
{
Console.WriteLine(“base display”);
}
}
Class D:B
{
Public new void print()
{
Console.WriteLine(“Derived Display”);
}
}
Class interfaceTest3
{
Public static void Main()
{
D d=new D();
d.print();
Display dis=(Display)d;
Vasudha GS, SRNMNC, Shimoga Page 33
Dis.print();
}
}

Explicit Interface Implementation:


➢ One of the reasons that c# does not support multiple inheritance is the problem
of name collision.
➢ This problem still persists in C# when it implements more than one interface.
Example:
Interface l1{ void Display(); }
Interface l2{ void display();}
Class C1:l1,l2
{
Public void Display{ }
}
➢ Does c.display() implement l1. Display(), or l2.Display()? . It is ambiguous
and so the compiler reports an error.
➢ Such problems of name collision may occur when we implement interfaces
from different sources.
➢ To solve this problem, c# supports a technique known as explicit interface
implementation.
➢ This technique allows a method to specify explicitly the name of the interface
it is implementing.
Example: Program to demonstrate explicit interface implementation:
Using System;
Interface i1
Vasudha GS, SRNMNC, Shimoga Page 34
{
Void display();
}
Interface i2
{
Void display();
}
Class c1:i1,i2
{
Void i1.Display()
{
Console.WriteLine(“i1 display”);
}
Void i2.Display()
{
Console.WriteLine(“i2 Display”);
}
}
Class interfaceTest4
{
Public static void Main()
{
C1 c=new C1();
I1 intrf1=(i1)c;
I1.Display;
I2 intrf2=(i2)c;
I2.Display();
Vasudha GS, SRNMNC, Shimoga Page 35
}
}
Abstract classes and interfaces:
➢ Like any other classes, an abstract class can use an interface in the base class
list.
➢ Interface methods are implemented as abstract methods:
Example:
Interface A
{
Void method();
}
Abstract class B:A
{
……….
……..
Public abstract void method();
}
Here, class B does not implement the interface method; it simply redeclares as a
public abstract method. It is the duty of the class that derives from B to override
and implement the method.
Interfaces are similar to abstract classes. We can convert an interfaces into an
abstract lass.
Example:
Interface A
{
Void print();
}
Vasudha GS, SRNMNC, Shimoga Page 36
This is identical to the following abstract class:
Abstract class B
{
Abstract public void print();
}
Here, a class can inherit from B instead of implementing the interface A.
However, the class that inherits B cannot inherit any other class directly. If it is
an interface, then the class can not only implement the interface but also use
another class as base class thus implementing in effect multiple inheritances.
Obtaining the Interface Reference: The AS keyword:
➢ AS keyword can be used to determine whether a given type supports an
interface or not.
➢ If the object can be treated as a specified interface, the reference to the
interface will be returned, otherwise it returns null reference.
Example:
Class example
{
public static void main(String [] args)
{
……….
……….
Hexagon hex2=new Hexagon(“Peter”);
Ipointy ipt=hex2 as Ipointy;
If(ipt!=NULL)
Console.WriteLine(“Implements interface Ipointy”);
Else
Console.WriteLine(“Does not Implement interface Ipointy”);
Vasudha GS, SRNMNC, Shimoga Page 37
}
}
Here, hexagon is class which is used to create an object hex2. Ipointy is an
interface. We are checking whether the interface Ipointy is implemented by the
class Hexagon by using AS keyword.
Obtaining the interface reference: The IS Keyword:
➢ We can check for an implementation of the interface using the IS keyword.
➢ The IS keyword returns the reference to an interface if the interface is
implemented.
➢ Otherwise it returns a null reference.
Example:
Class sample
{
public static void main(String [] args)
{
…….
……..
Shape [] s={new Hexagon(), new circle(), new Triangle(),nerw Cirlce()};
for(int i=0;i<s.length;i++)
{
s[i].draw();
If(s[i] is Ipointy)
Console.WriteLine(“ Object {0} is implementing Ipointy”, i);
Else
Console.WriteLine(“ Object {0} is implementing Ipointy”, i);
}

Vasudha GS, SRNMNC, Shimoga Page 38


}
Here, we are creating an array of interfaces and name of the array is s. Later we
are checking which of the classes in the list are implementing the interface
Ipointy using IS keyword and displaying its details.

Interfaces as parameters:
➢ Interfaces are valid .NET types.
➢ We may construct methods that take interfaces as parameters.
➢ Interfaces can also be used as method return values. For example, you could
write a method that takes any System.Object, checks for IPointy
compatibility, and returns a reference to the extractedinterface.
Example:
static IPointy ExtractPointyness(object o)
{
if (o is IPointy)
return (IPointy)o;
else
return null;
}
static void Main(string[] args)
{
// Attempt to get IPointy from Car object.
Car myCar = new Car();
IPointy itfPt = ExtractPointyness(myCar);
if(itfPt != null)
Console.WriteLine("Object has {0} points.", itfPt.Points);
else
Vasudha GS, SRNMNC, Shimoga Page 39
Console.WriteLine("This object does not implement IPointy");
}
Interface as Return values:
➢ Interface can also be used as method return values.
➢ For example, we can write a program that check for the implementation of an
interface and return its interface if it is implemented.
Example:
Static Ipointy IpointyCheck (Object o)
{
if( o is Ipointy)
Return(Ipointy)o;
Else
Return null;
}
Static void main(String [] args)
{
car c=new car();
Ipointy ipt=IpontyCheck(c);
If(ipt!=null)
Console.WriteLine(“car implements Ipointy”);
Else
Console.WriteLine(“car does not implement Ipointy”);
}
}

Array of interfaces:
Vasudha GS, SRNMNC, Shimoga Page 40
Understand that the same interface can be implemented by numerous types, even if
they are not within the same class hierarchy. This can yield some very powerful
programming constructs. For example, assume that you have developed a brand new
class hierarchy modeling kitchen utensils and another modeling gardening
equipment.
Although these hierarchies are completely unrelated from a classical
inheritance point of view, you can treat them polymorphically using interface-based
programming. To illustrate, assume you have an array of IPointy-compatible objects.
Given that these members all support the same interface,you are able to iterate
through the array and treat each object as an IPointy-compatible object,
regardless of the overall diversity of the class hierarchies:
static void Main(string[] args)
{
// This array can only contain types that
// implement the IPointy interface.
IPointy[] myPointyObjects = {new Hexagon(), new Knife(),
new Triangle(), new Fork(), new PitchFork()};
for (int i = 0; i < myPointyObjects.Length; i++)
Console.WriteLine("Object has {0} points.", myPointyObjects[i].Points);
}
The Interfaces of the System. Collections Namespace
➢ The simple Array class has a number of limitations, most notably it does not
dynamically resize itself as you add or clear items.
➢ The System. Collections namespace defines a number of interfaces. A
majority of the collection classes implement these interfaces to provide
access to their contents. The following table gives a list of the core
collection-centric interfaces.
Vasudha GS, SRNMNC, Shimoga Page 41
Sl.No System.Collections Interface Meaning
1 ICollection Defines geneic
characteristics for a
collection type.
2 IEqualityComparer Defines methods to
support the
comparison of
objects for equality.
3 IDictionary Allows an object to
represent its contenst
using name/value
pairs.
4 IEnumerable Returns the
IEnumerator
interface for a given
object.
5 IEnumerator Generally supports
foreach-
styleiterators for
subtypes.

6 IHashCode Provider Returns the hash


code for the
implementing type
using a customized
hash algorithm.

Vasudha GS, SRNMNC, Shimoga Page 42


7 IKeyComaparer This combines the
functionlaity of
IComaprer and
IHashCodeProvider
to allow objects to be
compared in a hash
code compatible
manner
8. IList Provides behavior to
add, remove and
index items in a list
of objects.

Many of these interfaces are related by an interface hierarchy, while others


are stand-alone entities. Following Figure shows the relationship between each type
:

Vasudha GS, SRNMNC, Shimoga Page 43


The Role of ICollection
➢ The ICollection interface is the most primitive interface of the
System.Collections namespace.
➢ In that it defines a behavior supported by a collection type. This interface
providesa small set of properties that allow you to determine
(a) the number of items in the container.
(b) the thread safety of the container
(c) the ability to copy the contents into a System.Arraytype.
Formally, ICollection is defined as follows :
public interface ICollection : IEnumerable
{
int Count { get; }
bool IsSynchronized { get; }
object SyncRoot { get; }
void CopyTo(Array array, int index);
}

The Role of IDictionary


➢ A dictionary is simply a collection that maintains a set of name/value pairs.
➢ IDictionary interface defines a Keys and Values property as well as Add(),
Remove(), and Contains() methods.
➢ The individual items may be obtained by the type indexer. Here is the formal
definition:
public interface IDictionary :
ICollection, IEnumerable
{
bool IsFixedSize { get; }
Vasudha GS, SRNMNC, Shimoga Page 44
bool IsReadOnly { get; }
object this[ object key ] { get; set; }
ICollection Keys { get; }
ICollection Values { get; }
void Add(object key, object value);
void Clear();
bool Contains(object key);
IDictionaryEnumerator GetEnumerator();
void Remove(object key);
}
The Role of IDictionaryEnumerator
➢ The IDictionary.GetEnumerator() returns an instance of the
IDictionaryEnumerator type.
➢ IDictionaryEnumerator is simply a strongly typed enumerator, given that it
extends IEnumerator by adding the following functionality:
public interface IDictionaryEnumerator : IEnumerator
{
DictionaryEntry Entry { get; }
object Key { get; }
object Value { get; }
}
IDictionaryEnumerator allows you to enumerate over items in the dictionary via
thegeneric Entry property, which returns a System.Collections.DictionaryEntry
class type. In addition,you are also able to traverse the name/value pairs using the
Key/Value properties.

Vasudha GS, SRNMNC, Shimoga Page 45


The Role of IList
The final key interface of System.Collections is IList, which provides the ability to
insert, remove, and index items into (or out of) a container:
public interface IList :
ICollection, IEnumerable
{
bool IsFixedSize { get; }
bool IsReadOnly { get; }
object this[ int index ] { get; set; }
int Add(object value);
void Clear();
bool Contains(object value);
int IndexOf(object value);
void Insert(int index, object value);
void Remove(object value);
void RemoveAt(int index);
}
The Class Types of System.Collections:
The following table shows classes of System.collections :
Sl.No Class Meaning Implementing
Intefaces
1 ArrayList Represents dynamically sized array of objects IList,
ICollection,
IEnumerable

Vasudha GS, SRNMNC, Shimoga Page 46


2 HashTable Represents a collection of objects identified IDictionary,
by a numeric key Icollection,
IEnumerable
4 Queue Represents a standard first-in first out queue. ICollection,
IClonable and
IEnumerable
and
ICollections
5 SortedList Like a dictionary. however the elements can IEnumerable
also be accessed by ordinal position and
ICollection,
IEnumerable
and IClonable
6 Stack A last in first out queue providing push and ICollection,
pop functionality IClonable and
IEnumerable.

Vasudha GS, SRNMNC, Shimoga Page 47

You might also like