Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

Remainder operation returns incorrect results in .NET Framework 3.5 and 4.0


Summary

When you use the modulus operator in the .NET Framework 3.5 or the .NET Framework 4.0, incorrect results are returned. Specifically, this issue occurs when you run the remainder operation and when you use certain 64-bit integer values under the x86 architecture.

The following sample code illustrates this problem:
class Program
{
static void Main(string[] args)
{
DoModulo();
}

public static void DoModulo()
{
const int LNXBASE = 100;
long longX = -856480339907;
var mod = longX % LNXBASE;
Console.WriteLine(mod);
}
}
Here the output is 93 instead of the correct result of -7.

↑ Back to the top


More Information

This issue is triggered by the remainder operation, and only for 64-bit integers under the x86 architecture. This issue does not affect other operations, and it has been fixed for the .NET Framework 4.5 under all architectures.

↑ Back to the top


Workaround

Because this issue has been fixed for the .NET Framework 4.5, we recommend that you upgrade if it's possible. If an upgrade is not possible, use one of the following workarounds:

  • Instead of using const int, use int.
  • Use static int.
Note the following corrected code:
class Program
{
static void Main(string[] args)
{
DoModulo();
}

static int LNXBASE = 100;

public static void DoModulo()
{
long longX = -856480339907;
var mod = longX % LNXBASE;
Console.WriteLine(mod);
}
}

↑ Back to the top


Keywords: kb

↑ Back to the top

Article Info
Article ID : 2912879
Revision : 1
Created on : 1/7/2017
Published on : 12/9/2013
Exists online : False
Views : 64