Reputation: 9526
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:
Warning CA1801
Parameter 'args' of 'Program.Main(string[])' is never used. Remove the parameter or use it in the method body.
ConsoleApplication1 …\Program.cs 14
Warning CA1804
'Program.Main(string[])' declares a variable, 'message', of type 'string', which is never used or is only assigned to. Use this variable or remove it.
ConsoleApplication1 …\Program.cs 15
Warning CA1801
Parameter 'messageToLog' of 'Program.Method(string)' is never used. Remove the parameter or use it in the method body.
ConsoleApplication1 …\Program.cs 22
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
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
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