Search

Cast an object to an interface

This C# code snippet shows how to test the specified object in order to determine whether or not it implements a particular interface. Although an interface cannot be instantiated directly, an interface can be treated polymorphically by casting an object which implements the interface to the interface type. Then, the actual runtime type of the object can be ignored; and, the object will appear to be an instantiated interface. The first option is to simply cast the object reference to an interface
ICloneable iCloneable = (ICloneable) new TheObject();

Unfortunately, if the object does not implement that particular interface, a runtime error of System.InvalidCastException will be thrown. You could catch that exception and take appropriate action; but, that is both bad practice and inefficient.

The second option is to use the is operator which returns true if the object can be safely cast to the specified type:
using System;
TheObject theObject = new TheObject();  
if (theObject is ICloneable)
{
   ICloneable iCloneable = (ICloneable) theObject;  
}
else
{
   console.WriteLine ("Interface unsupported");
}
The third option is to use the as operator which will either cast the object to the specified type or return a null if the cast would be invalid.
ICloneable iCloneable = new TheObject() as ICloneable;
if (iCloneable != null)
{
   iCloneable.Clone();   // access interface member
}
else
{
   console.WriteLine ("Interface unsupported");
}