MultiplyBy

public static Int32 MultiplyBy(this Int32 thisNumber,  

                                    Int32 otherNumber)

{

   long result = (long)thisNumber * (long)otherNumber;

   if (result > (long) Math.Pow(2,31) - 1)

      throw new InvalidOperationException(

         "Product result is larger than an Int32 value.");

    return (Int32) result;

}

Example:
//results in -1651507200
int a = 2000000000;
int b = a*a;

//results in exception
int a = 2000000000;
int b = a.MultiplyBy(a);

Description

A simple multiplication extension. Backing idea is to overcome the ridiculous flaw in the Int32 value type when a regular multiplication overflows the Int32 value range. Along these lines it would also be possible to gracefully return larger values as e.g. longs, or as BigInt (when the BCL team gets around to implementing it ;-). But the example here sticks to the bounds of the Int32 range.

Details

Double click on the code to select all.

 

;