Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Multiplying two variables of value int.MaxValue does not result in OverflowException

Tags:

c#

int

I've got an integer array that contains two values, each the maximum value of int32:

int[] factors = new int[] { 2147483647, 2147483647 };

I'm trying to get the product of these two numbers to create an OverflowException:

try
{
    int product = factors[0] * factors [1];
}
catch(Exception ex)
{
}

Much to my surprise (and dismay), product actually returns a value of 1. Why is this, and how would I go about throwing an exception when the product of two integers exceeds int.MaxValue?

like image 453
Jonathan Shay Avatar asked Dec 25 '22 23:12

Jonathan Shay


1 Answers

Because the default behavior of C# is not to check overflow with int. However, you can force overflow checking by using checked keyword.

try
{
    checked
    {
        int product = factors[0] * factors [1];
    }
}
catch(Exception ex)
{
}
like image 122
Cédric Bignon Avatar answered Feb 15 '23 23:02

Cédric Bignon