Answered Sum/Average does not check for overflow

  • Sunday, September 18, 2005 11:33 PM
     
     

    Why  Sum / Average run in unchecked context ?

    I.e.

    long[] numbers = { long.MaxValue/2, long.MaxValue/2, long.MaxValue/2};

    var averageNum = numbers.Average();

    Result in  -1,53722867280913E+18.

     

    int[] numbers = { int.MaxValue/2 , int.MaxValue/2 , int.MaxValue/2};

    var numSum = numbers.Sum();

    Result in -1073741827

     

    Any reasons for this ?

All Replies

  • Monday, September 19, 2005 8:13 AM
     
     
    Presumably because it's faster and more flexible.

    You can wrap the whole thing in a checked block yourself, or enable the compiler option, and then the calculation will be checked.

    If the methods were defined as checked then you wouldn't have the option to run them unchecked.
  • Monday, September 19, 2005 10:23 AM
     
     Answered

    I don't see smiles in your posting ;-)

    Your suggestion to change compiler option or run everything in checked block will have effect only on your sources - not libraries ! Plz validate your answers before posting :-(