Kyle Isgorener
Kyle Isgorener

Reputation: 31

Why there is no compile time error despite having an obvious overflow with arithmetic operators

When working with arithmetic operators in c# I noticed that there is no compile time error but an obvious runtime one. Is there any way to notice this kind of overflow exceptions as a compile time error when converting integral types to each other?

static void Main(string[] args)
{
    byte[] myArray = new byte[10];

    for (byte counter = 0; counter < myArray.Length; counter++)
    {
        myArray[counter] = Convert.ToByte(counter + 300);
    }

    foreach (int member in myArray)
    {
        Console.WriteLine(member);
    }
 }

Obviously when you run this code because it'll try to store a value over 300 in a byte, you'll get an OverflowException due to its 256 limitation.

Upvotes: 1

Views: 92

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273844

Note that the compiler just sees

public static byte ToByte (int value);

It would be a feature request to make the compiler 'understand' that ToByte() method. That feature would never be complete. How about byte.Parse("300") ?

It would be more reasonable to ask the compiler to catch a cast conversion, like

myArray[counter] =  (byte) (counter + 300);

but it won't do that either. counter could be -200.

In this case it knows the range for counter because it belongs to a for-loop. But how many codepaths should it check otherwise? It would be a feature that could only work some of the time.

Upvotes: 3

Related Questions