We have a project where we use StyleCop and Code analysis to verify the structure of our code. We have set treat warnings as errors for both mechanisms.
We discover however a strage behaviour which we cannot explain. We have a debug and a release configuration. On our debug configuration we didn't get one CA warning while we get this warning on our release configuration. We started to look at the differences between those 2 configurations and we discovered the optimize checkbox was the difference why we got this warning during release but not during debug.
We have the configuration below.
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
When we set the optimize value to true for debug we also the CA warning. When we set this to false the warning is gone. This is also only applicable for warning CA1806. Other CA warnings are correctly show regardless of the optimize value.
The code triggering this warning is the code below. This is just testing code but it simulates the real situation we had. A variable which has assigned a default value but is never used in any code.
public CourseService(IOrtContext context)
{
this.context = context;
var defaultDate = new DateTime(1900, 1, 1);
}
So, does anybody know why CA1806 is shown dependent on whether optimize is enabled or not?
I believe that's because the optimizer completely elides the assignment to
defaultDate
.In debug mode, a new
DateTime
is instantiated and is assigned to thedefaultDate
local variable:The assignment is considered as a "use" of the
DateTime
instance, soCA1806
is not raised, even ifdefaultDate
is subsequently not used.On the other hand, the optimizer elides the assignment (and the local variable) in release mode:
Therefore the
DateTime
instance is not considered as "used" anymore, andCA1806
is raised.