Kasper van den Berg
Kasper van den Berg

Reputation: 9526

Suppress code analysis warnings for conditional methods

Running code analysis (Visual Studio 2015) on code that calls Conditional methods causes warnings for unused locals (CA1804) or unused parameters (CA1801). E.g. for:

using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        [Conditional ("NEVER_DEFINED")]
        static void Log(string message)
        {
            System.Console.WriteLine("Demo conditional message logging: " + message);
        }

        static void Main(string[] args)
        {
            string message = "Only log this when `NEVER_DEFINE` is #defined";
            Log(message);

            Method("other message");
        }

        static void Method(string messageToLog)
        {
            Log(messageToLog);
        }
    }
}

Code Analysis results in:

I consider the warnings about message and messageTolog as false positives. Is there a way to have the code analysis treat the conditional methods as using the parameters?

Upvotes: 2

Views: 3660

Answers (2)

Kasper van den Berg
Kasper van den Berg

Reputation: 9526

Add the CODE_ANALYSIS conditional attribute to the called conditional method, e.g.:

using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        [Conditional ("NEVER_DEFINED")]
        [Conditional ("CODE_ANALYSIS")]
        static void Log(string message)
        {
            System.Console.WriteLine("Demo conditional message logging: " + message);
        }

        static void Main(string[] args)
        {
            string message = "Only log this when `NEVER_DEFINE` is #defined";
            Log(message);

            Method("other message");
        }

        static void Method(string messageToLog)
        {
            Log(messageToLog);
        }
    }
}

Now Log(string) is considered using its parameters and all parameters and local variables supplied to it are considered used as well.

Upvotes: 1

Kasper van den Berg
Kasper van den Berg

Reputation: 9526

You can use the [SuppressMessageAttribute] in System.Diagnostics.CodeAnalysis. However you would have to apply it to each method that calls the Conditional-method (or apply it at broader scope); e.g.:

[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Performance", "CA1804")]
static void Main(…)
{
    …
}

[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Performance", "CA1801")]
static void Method(…)
{
    …
}

Upvotes: 3

Related Questions