S1848 — Objects should not be created to be dropped immediately without being used

Language
C#
Type
Bug
Severity
Major

Why is this an issue?

Creating objects that are not used is a vulnerability that can lead to unexpected behavior.

If this was done intentionally due to side effects in the object’s constructor, the code should be moved to a dedicated method.

How to fix it

Code examples

Noncompliant code example


public void Method(MyObject myObject)
{
    if (myObject is null)
    {
        new MyObject(); // Noncompliant
    }

    if (myObject.IsCorrupted)
    {
        new ArgumentException($"{nameof(myObject)} is corrupted"); // Noncompliant
    }

    // ...
}

Compliant solution


public void Method(MyObject myObject)
{
    if (myObject is null)
    {
        myObject = new MyObject(); // Compliant
    }

    if (myObject.IsCorrupted)
    {
        throw new ArgumentException($"{nameof(myObject)} is corrupted"); // Compliant
    }

    // ...
}

↑ Back to top