I have a situation where the c# compiler is doing some strange stuff when optimisation is turned on (ie in release mode) and you start stepping through the code (with Enable just my code turned off)
I have code similar to the following, what it does is basically see if the settings provider has an application environment that it wants to set, otherwise it leaves the environment alone.
var environmentValue = settingsProvider.ApplicationEnvironment;
if (!string.IsNullOrWhiteSpace(environmentValue))
{
switch (environmentValue.ToLower())
{
case "p":
_connectionSettings.Production();
break;
case "t":
_connectionSettings.Test();
break;
case "d":
_connectionSettings.Development();
break;
case "l":
_connectionSettings.Local();
break;
}
}
However when optimisations is turned on it is always hitting the last case statement even when the value of environmentValue is null i.e., shouldn't be getting into the switch in the first place.
I've had to change the code so that it is like this instead, and it now hits the default: case instead.
var environmentValue = settingsProvider.ApplicationEnvironment;
if (!string.IsNullOrWhiteSpace(environmentValue))
{
switch (environmentValue.ToLower())
{
case "p":
_connectionSettings.Production();
break;
case "t":
_connectionSettings.Test();
break;
case "d":
_connectionSettings.Development();
break;
case "l":
_connectionSettings.Local();
break;
default:
Console.WriteLine(environmentValue);
break;
}
}
I'm running this through Visual Studio 2015, Framework version 4.5.1, Release Mode, Any CPU (prefer 32 bit), and Enable Just My Code turned off.
When I first started this post I didn't realise that it was only when stepping through the code. It does seem to have some strange behaviour though since I wasn't stepping through the code and was still hitting the last case statement.
I've also created a gist project which illustrates the issue.
https://gist.github.com/matthewvukomanovic/899d595cd0b787116b95ddb5f2b128d3#file-program-cs
With the test application I've written it only needs another call afterwards which will force it to behave correctly, however in the real application it already has other calls which use that same object, however it doesn't work quite the same.
Does anyone know how to avoid this issue when stepping through optimised code, apart from adding a dummy default case like I have?