Inappropriate casts are issues that will lead to unexpected behavior or runtime errors, such as InvalidCastExceptions. The compiler
will catch bad casts from one class to another, but not bad casts to interfaces. Nor will it catch nullable values that are known to be null but that
are cast to their underlying value types anyway.
It is much better to use the as operator because it will return null instead of throwing an exception.
public interface IMyInterface
{ /* ... */ }
public class Implementer : IMyInterface
{ /* ... */ }
public class MyClass
{ /* ... */ }
public static class Program
{
public static void Main()
{
var myclass = new MyClass();
var x = (IMyInterface) myclass; // Noncompliant, InvalidCastException is being thrown
var b = myclass is IMyInterface; // Noncompliant, always false
int? i = null;
var ii = (int)i; // Noncompliant, InvalidOperationException is being thrown
}
}
public interface IMyInterface
{ /* ... */ }
public class Implementer : IMyInterface
{ /* ... */ }
public class MyClass
{ /* ... */ }
public static class Program
{
public static void Main()
{
var myclass = new MyClass();
var x = myclass as IMyInterface; // Compliant, but will always be null
var b = false;
int? i = null;
if (i.HasValue)
{
var ii = (int)i;
}
}
}
No issue is reported if the interface has no implementing class in the assembly.