DEV Community

Cover image for How to catch OverflowExceptions when casting values in .NET
Vinicius Rocha
Vinicius Rocha

Posted on

How to catch OverflowExceptions when casting values in .NET

Introduction

It is important to understand what happens when we cast numeric values in .NET, the result might not be what you are expecting. Here, I am showing how to use OverflowException to prevent unexpected behaviors.

The Default Behavior

When writing code in C#, if we cast a numeric value to another type that doesn't not have enough bits to represent it, the compiler will truncate the number to the maximum value supported.

For example:

using System;

class Program
{
  static void Main(string[] args)
  {
    long longValue = long.MaxValue;
    Console.WriteLine((byte)longValue);
  }
}

// Output: 255
Enter fullscreen mode Exit fullscreen mode

Validate using OverFlowExceptions

In order to ensure that the cast will not silently change the value, we need to wrap the code into a check block.

using System;

class Program
{
  static void Main(string[] args)
  {
    long longValue = long.MaxValue;
    try
    {
      checked
      {
        Console.WriteLine((byte)longValue);
      }
    }
    catch (OverflowException)
    {
      Console.WriteLine($"Unable to cast {longValue} to byte.");
    }
  }
}

// Output: Unable to cast 9223372036854775807 to byte.
Enter fullscreen mode Exit fullscreen mode

Wrapping the code inside a check block will ensure that it will throw an exception if the value is too big for the target type. For more information, check out the official documentation.

Top comments (0)