Information Technology Reference
In-Depth Information
An Interface Is a Reference Type
An interface is more than just a list of members for a class or struct to implement. It is a refer-
ence type.
You cannot access an interface directly through the class object's members. You can,
however, get a reference to the interface by casting the class object reference to the type of the
interface. Once you have a reference to the interface, you can use dot-syntax notation with
the reference to call interface members.
For example, the following code shows an example of getting an interface reference from
a class object reference.
In the first statement, variable mc is a reference to a class object that implements inter-
face IIfc1 . The statement casts that reference to a reference to the interface and assigns
it to variable ifc .
￿
￿
The second statement uses the reference to the interface to call the implementation
method.
Interface Cast to interface
IIfc1 ifc = (IIfc1) mc; // Get ref to interface
Interface ref Class object ref
ifc.PrintOut ("interface"); // Use ref to interface to call member
Use dot-syntax notation to call through the interface reference.
For example, the following code declares an interface and a class that implements it. The
code in Main creates an object of the class, and calls the implementation method through the
class object. It also creates a variable of the interface type, casts the reference of the class object
to the interface type, and calls the implementation method through the reference to the
interface.
Search WWH ::




Custom Search