Test for an interface implementation

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
C# Code Snippets

C# Source Code Bank

See also …
edit

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—e.g. ICloneable—and hope for the best:

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:

TheObject theObject = new TheObject();  
if (theObject is ICloneable)
{
   ICloneable iCloneable = (ICloneable) theObject;  
}
else
{
   console.WriteLine ("Interface unsupported");
}

Note: The C# is operator is the equivalent of the Java instanceof operator

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");
}

Visual C# Best Practices

  • Use the as operator when the normal program flow is to test for the interface and—immediately—cast the object for access to the interface members.
  • Use the is operator when the normal program flow is to test for the interface; but, interface member access is either delayed or does not occur at all.


Personal tools