rspec/rules/S1944/csharp/rule.adoc

99 lines
2.4 KiB
Plaintext
Raw Normal View History

== 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.
2020-06-30 12:47:33 +02:00
It is much better to use the `as` operator because it will return `null` instead of throwing an exception.
2020-06-30 12:47:33 +02:00
=== Noncompliant code example
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:47:33 +02:00
----
public interface IMyInterface
2020-06-30 12:47:33 +02:00
{ /* ... */ }
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
2020-06-30 12:47:33 +02:00
}
}
----
=== Compliant solution
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:47:33 +02:00
----
public interface IMyInterface
2020-06-30 12:47:33 +02:00
{ /* ... */ }
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
2020-06-30 12:47:33 +02:00
var b = false;
}
}
----
=== Exceptions
2020-06-30 12:47:33 +02:00
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[]