99 lines
2.4 KiB
Plaintext
99 lines
2.4 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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.
|
|
|
|
It is much better to use the `as` operator because it will return `null` instead of throwing an exception.
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,csharp]
|
|
----
|
|
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
|
|
}
|
|
}
|
|
----
|
|
|
|
=== Compliant solution
|
|
|
|
[source,csharp]
|
|
----
|
|
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;
|
|
}
|
|
}
|
|
----
|
|
|
|
=== Exceptions
|
|
|
|
No issue is reported if the interface has no implementing class in the assembly.
|
|
|
|
include::../see.adoc[]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
* Review this cast; in this project there's no type that implements both "{0}" and "{1}".
|
|
* Review this cast; in this project there's no type that extends "{0}" and implements "{1}".
|
|
* Nullable is known to be empty, this cast throws an exception.
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 11 Dec 2015, 08:58:50 Tamas Vajk wrote:
|
|
\[~ann.campbell.2] applied some changes to the description
|
|
|
|
=== on 11 Dec 2015, 13:57:58 Ann Campbell wrote:
|
|
looks good
|
|
|
|
=== on 21 Jul 2016, 14:39:03 Ann Campbell wrote:
|
|
\[~tamas.vajk] I've tweaked the wording of your addition. Please double-check me.
|
|
|
|
=== on 21 Jul 2016, 15:24:29 Tamas Vajk wrote:
|
|
\[~ann.campbell.2] "known-empty" is strange for me, I would probably go with simply "empty" if the original variant was not good.
|
|
|
|
=== on 21 Jul 2016, 15:38:42 Ann Campbell wrote:
|
|
Second attempt made [~tamas.vajk]
|
|
|
|
=== on 21 Jul 2016, 15:41:08 Tamas Vajk wrote:
|
|
\[~ann.campbell.2] perfect, thanks.
|
|
|
|
include::../comments-and-links.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|