What is checked in the code in C#?

Asked

Viewed 529 times

14

I saw a code:

using (IEnumerator<TSource> e = source.GetEnumerator()) {
     checked {
         while (e.MoveNext()) count++;
     }
}

What is the purpose of the code checked {} in that code C#?

2 answers

15


The checked is used to determine whether the arithmetic overflow will be considered as an error. Then if the value passes the limit that the type supports an exception it will be thrown preventing the value from being used inadvertently. For performance reasons the default is to issue no exception and let the code go wrong.

Obviously this mode is only active within the block bounded by the keys.

The cases he needs are rare. It can be useful in cases that will almost never occur the problem, but when it occurs it is good that it does not "pass beaten". The most common is to ensure that it does not burst. Interestingly to check before is less performatic since there is a reasonable cost to make a branch (if). If you don’t make the exception, you’ll be faster. If you throw the exception will be very slow. We should always avoid exceptions until it makes a lot of sense.

There is also the unchecked to rule out errors. Obviously, if no error occurs, the calculation may produce unexpected results. It is only needed when code is compiled with /checked turned on, changing the pattern, so if you want to turn off at any specific point you have to do the point shutdown. It is almost never used.

Eric Lippert’s articles, who is the authority on the subject, talk about the details. Part 1 and Part 2.

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • What is inadvertently?

  • @Virgilionovic carelessly, without waiting: http://www.dicionarioinformal.com.br/inadvertently/, https://www.dicio.com.br/inadvertently/, http://www.sinonimos.com.br/inadvertently/,

  • got it now @bigown, didn’t know it! I thought it was typo.

  • @Virgilionovic warning -> warning, science; warned-> you are aware; inadvertent -> is not aware, occurs in your absence; inadvertently -> inadvertent form -> occurs without you noticing.

6

The keyword checked is used to explicitly allow the overflow check of integral types of arithmetic operations and conversions.

By default, an expression that contains only constant values causes a compiler error if the expression produces a value that is outside the target type range. If the expression contains one or more non-constant values, the compiler does not detect the overflow. Example:

int x = int.MaxValue;  
int y = x + x;          
Console.WriteLine(y);   

Put this stretch into a checked block prevents overflow, and instead the runtime launches an Overflowexception:

checked 
{ 
     int x = int.MaxValue; 
     int y = x + x; 
     Console.WriteLine(y); 
} 

You can treat the exception by adding blocks try catch:

checked 
{ 
    try 
    { 
        int x = int.MaxValue; 
        int y = x + x; 
        Console.WriteLine(y); 
    } 
    catch (Exception  exception) 
    { 
        Console.WriteLine(exception); 
    } 
} 

The unchecked keyword is used to suppress overflow check for integral type arithmetic operations and conversions.

In a context unchecked, if an expression produces a value that is outside the target type range, the overflow is not signalled.

The "ideal" solution would be to use the unchecked along:

checked 
{ 
    try 
    { 
        int x = int.MaxValue; 
        int y = x + x; 
        Console.WriteLine (y); 
    } 
    catch (Exception  exception) 
    { 
        Console.WriteLine (exception); 
    } 

    unchecked 
    {
        int z = 2 + 10 ; 
        Console.WriteLine(z); 
    } 

} 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.