All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S3443.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

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:

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

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

void ExamineSystemType(string str)
{
    Type stringType = str.GetType();

    if (stringType.IsInstanceOfType(str)) // Compliant
    { /* ... */ }
}

Resources

Documentation

Articles & blog posts





© 2015 - 2024 Weber Informatics LLC | Privacy Policy