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