65 lines
1.5 KiB
Plaintext
65 lines
1.5 KiB
Plaintext
Inappropriate casts are issues that will lead to unexpected behavior or runtime errors, such as ``InvalidCastException``s. 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.
|
|
|
|
== Noncompliant Code Example
|
|
|
|
----
|
|
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
|
|
}
|
|
}
|
|
----
|
|
|
|
== Compliant Solution
|
|
|
|
----
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
----
|
|
|
|
== Exceptions
|
|
|
|
No issue is reported if the interface has no implementing class in the assembly.
|
|
|
|
include::../see.adoc[]
|