ExtensionMethod.NET Home of 876 C#, Visual Basic, F# and Javascript extension methods


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.


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;



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

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

Author: Arjan Keene

Submitted on: 20 feb. 2008

Language: C#

Type: System.Int32

Views: 4805