In my Visual Studio 2015 I create a new Windows.Forms application (not a console application) and do nothing else than adding two lines of code using the % operator within a self assigning + or - operation (e.g. to make a number even). The result is an Invalidprogramexception when I launch this as a Release build with 'optimize code' (which is the default).
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
int a = 0, b;
a += a % 2; // b = a + a % 2; also crashes.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Again: This only crashes if I launch the Release build. As soon as I uncheck 'Optimize code' in the Build settings, it works fine, so obviously the optimizer confuses the code. Changing the code slightly makes things either work or not work, depending on the code. I checked various Framework versions (2.0 to 5.4.1) it is the same thing all over the place. And it happens not only in the example above - it occurred to me in a big Forms application somewhere in the regular code.
Of course it would be easy to rearrange code in a way that it does not crash for now. But I would very much like to gain an understanding of the problem, because how can you feel safe with % operator if such things happen?
I searched the internet for this problem a lot now but have not found anything about it. I would be happy already if someone here could confirm this issue or otherwise tell me that I am hallucinating. All fine, because right now I feel totally lost.