Ad

Firstly, if this method is to validate that the multiplication between two integers results in a valid integer, this method should return an integer. If all you wanted was multiplication of two integers resulting in a Long, then Math.BigMul() already does this; the optimal code is a one line implementation using that library. Notice BigMul completes the operation you were performing, but is a much cleaner implementation.

Secondly, your code to handle errors here is unnecessary and an "InvalidOperation" is too generic (more specifically its an OverflowException).

Convert helper from long to Int32 already handles OverflowExceptions for operations. You can remove your "InvalidOperation" logic and use the already existing library which will properly throw an OverflowException if the result is too large to return as an integer.

Code
Diff
  • using System;
    
    public class Multiplication
    {
        // Multiply two integers
        // Throws error if the product is outside of the int range.
        // This would otherwise silently error and return the wrong product.
        public int Multiply(int a, int b) {
          long res = Math.BigMul(a, b);
          
          // Convert.ToInt32 throws OverFlowException if conversion is out of the bounds of the integer.
          return Convert.ToInt32(res);
        }
    }
    • using System;
    • public class Multiplication
    • {
    • // Multiply two integers
    • // Throws error if the product is outside of the int range.
    • // This would otherwise silently error and return the wrong product.
    • public long Multiply(int a, int b) {
    • long res = (long)a * (long)b;
    • public int Multiply(int a, int b) {
    • long res = Math.BigMul(a, b);
    • // make sure it's still a valid int
    • if (res > Int32.MaxValue || res < Int32.MinValue)
    • throw new InvalidOperationException("Product is outside range of int");
    • return res;
    • // Convert.ToInt32 throws OverFlowException if conversion is out of the bounds of the integer.
    • return Convert.ToInt32(res);
    • }
    • }