1

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.

H H
  • 263,252
  • 30
  • 330
  • 514
  • No. An array can be any size. The compiler does not know the size of inputs and only can detect array overflows at run time. You can improve you code by make 10 a constant like const int ARRAY_SIZE = 10; Then test to make sure 300 > ARRAY_SIZE. The issue is you are hard coding number that should be constant which can be compared by the compiler. – jdweng Dec 31 '18 at 14:36
  • 2
    @jdweng He's talking about the max value of byte not the array. He just spoke wrong. `Convert.ToByte(t + 300) Value was either too large or too small for an unsigned byte.` – Shelby115 Dec 31 '18 at 14:37
  • Compiler is not that smart – Cleptus Dec 31 '18 at 14:37
  • [This post](https://stackoverflow.com/questions/2382155/c-sharp-net-is-it-possible-to-create-compile-time-warnings-when-property-is-se) about creating your own compiler errors/warnings is probably as close as you can get with C#. – Sudsy1002 Dec 31 '18 at 14:39
  • 1
    `Convert.To()` is just another function. If the compiler was expected to check the result we'd be here all day. What is in place to tell the compiler to check the result of `Convert.ToByte` and not some function I create like `DoSomeStuff()`? – Shelby115 Dec 31 '18 at 14:39
  • If you set the length of myArray to be 256 instead of 10, I doubt you'd get either error. – justin.m.chase Dec 31 '18 at 14:40
  • 1
    Surprising how many commenters think this is about the length of the array. Maybe just ask about `byte b = Convert.ToByte(counter + 300);` – H H Dec 31 '18 at 14:42

1 Answers1

3

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.

H H
  • 263,252
  • 30
  • 330
  • 514