Unit 3-1
Unit 3-1
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();
}
Exception:
➢ An exception is a condition that is caused by the runtime error in the program.
Statements that
causes exception
Throws
Exception
Catch block
Object
Statements that
handles the exception
}
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.
}
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);
}
}
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());
}
}
}
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();
}
}
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.