C#


CSHARP.STRUCT.UUOBJ : Unused Object (C#)

Summary

An object is created and not assigned, and its construction has no side-effects other than on the object itself.

C# allows a few expressions to be used as commands. Among them, object creation is allowed to be used as a command since it can in principle induce side-effects and hence have a computational sense. However, creation of objects that do not induce side-effects is useless and should be removed from the code; it might actually be the sign of a programming error.

Properties

Class Name Unused Object (C#)
Significance reliability
Mnemonic CSHARP.STRUCT.UUOBJ
Categories
CWE CWE:1164 Irrelevant Code
Availability Available for C# only.
Enabling Checks for this warning class are enabled by default. To disable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += discard class="Unused Object (C#)"

Example

using System;

namespace DocumentationExamples
{

    public class UselessConstruction
    {
        public static bool unnamed;
        public static void Main(string[] args)
        {
            UselessConstructionTest test = new UselessConstructionTest(args.Length > 0 ? args[0] : null); // ok: assigned to local variable
            new UselessConstructionTest("hello");                  // "Unused Object (C#)" warning issued here 
            new UselessConstructionTest();                                                                // ok: has side effect on static field UselessConstruction.unnamed
            Console.WriteLine(test);
        }
        class UselessConstructionTest
        {
            public readonly string name;
            public UselessConstructionTest(string name)
            {
                this.name = name;
            }
            public UselessConstructionTest()
            {
                name = "no name";
                unnamed = true;
            }
            public override string ToString()
            {
                return name;
            }
        }
    } @Override
    public String toString() {
      return name;
    }
  }
}

Resolution

Check if the object creation was meant to have some side-effect and delete it.

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.