rspec/rules/S3443/csharp/rule.adoc
2023-06-07 15:41:34 +02:00

88 lines
2.3 KiB
Plaintext

== Why is this an issue?
Calling `GetType` on a `Type` variable will always return the `System.Type` representation, which is equivalent to `typeof(System.Type)`. This also applies to passing a `Type` argument to `IsInstanceOfType` which always returns `false`.
In both cases, the results are entirely predictable and should be avoided.
=== Exceptions
Calling `GetType` on `System.Type` is considered compliant to get an instance of `System.RuntimeType`, as demonstrated in the following example:
[source,csharp]
----
typeof(Type).GetType(); // Can be used by convention to get an instance of 'System.RuntimeType'
----
== How to fix it
Make sure the usage of `GetType` or `IsInstanceOfType` is invoked with the correct variable or argument type.
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
void ExamineSystemType(string str)
{
Type stringType = str.GetType();
Type runtimeType = stringType.GetType(); // Noncompliant
if (stringType.IsInstanceOfType(typeof(string))) // Noncompliant; will always return false
{ /* ... */ }
}
----
==== Compliant solution
[source,csharp,diff-id=1,diff-type=compliant]
----
void ExamineSystemType(string str)
{
Type stringType = str.GetType();
if (stringType.IsInstanceOfType(str)) // Compliant
{ /* ... */ }
}
----
== Resources
=== Documentation
* https://learn.microsoft.com/en-us/dotnet/api/system.type["Type" class]
* https://learn.microsoft.com/en-us/dotnet/api/system.object.gettype["GetType" Method]
* https://learn.microsoft.com/en-us/dotnet/api/system.type.isinstanceoftype["IsInstanceOfType" Method]
=== Articles & blog posts
* https://stackoverflow.com/a/5737947[Difference between "System.Type" and "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[]