rspec/rules/S3443/csharp/rule.adoc

65 lines
1.5 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
If you call ``++GetType()++`` on a ``++Type++`` variable, the return value will always be ``++typeof(System.Type)++``. So there's no real point in making that call. The same applies to passing a type argument to ``++IsInstanceOfType++``. In both cases the results are entirely predictable.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
var intType = typeof(int);
var runtimeType = intType.GetType(); // Noncompliant, always typeof(System.RuntimeType)
var s = "abc";
if (s.GetType().IsInstanceOfType(typeof(string))) // Noncompliant; false
{ /* ... */ }
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
var s = "abc";
if (s.GetType().IsInstanceOfType("string"))
{ /* ... */ }
----
=== Exceptions
2021-04-28 16:49:39 +02:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
typeof(Type).GetType(); // Can be used by convention to get an instance of System.RuntimeType
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Remove this use of "GetType" on a "System.Type".
* Pass an argument that is not a "System.Type" or use "IsAssignableFrom".
* Remove the "GetType" call, it's suspicious in an "IsInstanceOfType" call.
=== Highlighting
* ``++.GetType()++``
* argument to ``++IsInstanceOfType++``
'''
== Comments And Links
(visible only on this page)
=== on 8 Dec 2015, 09:00:32 Tamas Vajk wrote:
\[~ann.campbell.2] I made some changes (description/title), could you run through them? Thanks
endif::env-github,rspecator-view[]