Wednesday, August 29, 2007

Interface : Using the is and the as Operators

Some times it is not clear whether a reference to an interface does in fact have access to the class' object. This condition may be checked by using the is or the as operator. For example suppose that a program has a class: theClass and it is derived from the interface: Interface. Then the question is whether theReference of Interface can be used to access an object of theClass in the following:



theClass theClassReference = new theClass();
Interface theReference = (Interface) theClassReference;




Further suppose that theClass has a method: theMethod(). What is desired is whether:



theReference.theMethod();




is syntactically correct. If it is not, then an exception of type: System.InvalidCastException is thrown. (More will be said about exceptions in a later lecture.)

To prevent this exception from occurring, this relationship could be tested prior to implementing the type casting and the call of the method: theMethod() by theReference using the following code:



if((theClassReference is Interface)
{
Interface theReference = (Interface) theClassReference;
theReference.theMethod();
}




As a result of the above, theReference would only call theMethod() should theClass have implemented the interface: Interface.

The operator as works similar to is. Using as, the above could be implemented in the following manner:



theClassReference = new theClass();
Interface theReference = theClassReference as Interface;
if(theReference != null)
theReference.theMethod();




In this if( ) statement theReference would be null should it not represent the object of theClass to which theClassReference refers.

No comments: