What is the point of using checked here

Can anyone clarify the following statement:

byte[] buffer = new Byte[checked((uint)Math.Min(32 * 1024, (int)objFileStream.Length))]; 

why shouldn't i use

 byte[] buffer = new Byte[32 * 1024]; 
+8
c #
source share
1 answer

An attempt was made to throw an exception if objFileStream.Length returns a number greater than int.MaxValue (2147483647), because Length on Stream returns a long type (I assume that objFileStream is a stream). In .net, arithmetic overflow is not checked by default.

The following code demonstrates this case:

 long streamLength = long.MaxValue; //suppose buffer length is big var res = checked( (int)(streamLength + 1) ); //exception will be thrown Console.WriteLine( res ); //will print 0 in you comment checked keyword 

After a short analysis, you can reduce the following statement

 new Byte[checked((uint)Math.Min(32 * 1024, (int)objFileStream.Length))]; 

to

 new Byte[Math.Min(32 * 1024, checked((int)objFileStream.Length))]; 

Personal recommendations: I do not see how OverflowException will help you here. Math.Min will depend on the fact that no more than 32768 elements will be created. If you try to catch somewhere in the calling method, you cannot determine the cause of this error, it can come from anywhere in the called stack.

Therefore, you probably do not have to always allocate an array of size 32768, as you suggested

 byte[] buffer = new Byte[32 * 1024]; 

but use Math.Min to save storage if objFileStream.Length returns a small number

 byte[] buffer = new Byte[Math.Min(32 * 1024, objFileStream.Length)]; 
+5
source share

All Articles