Sum/Average does not check for overflow

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



Answer this question

Sum/Average does not check for overflow

  • Beaver01

    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 :-(


  • blackwing

    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.

  • Sum/Average does not check for overflow