If you are seeking for a carry behavior, other answers/comments cover that pretty well. However, I find the original question to be an interesting brain puzzle (although not practically useful), specifically what is the best performance pure C# way to detect 2 signed integers add overflow. Ideally it would generate a minimum IL instructions with no branches. Here is the best I ended up - one with bool flag (true when overflow, false otherwise) and another with int "bit" (1 when overflow, 0 otherwise). Both satisfy the above criteria, "bit" version has few less IL instructions. Enjoy:-)
static int Add(int a, int b, out bool overflowFlag)
{
unchecked
{
int c = a + b;
overflowFlag = ((a ^ b) >= 0) & ((a ^ c) < 0);
return c;
}
}
static int Add(int a, int b, out int overflowBit)
{
unchecked
{
int c = a + b;
overflowBit = (int)((uint)((a ^ c) & ~(a ^ b)) >> 31);
return c;
}
}
BigIntegerclass in C#, or are you doing this just for practice?