Understanding of Checked and Unchecked Statement Type of C# (C Sharp)

In your day to day coding, you might perform many arithmetic conversions using explicit casting. This might lead to overflow at certain cases or it might lead to truncation. You might have accepted the default behavior of your application.




But is there any ways where you have the control of checking overflow or eliminating the check for overflow irrespective of the default nature? Yes, C# provides you this option of gaining control over checking and handling the overflow. C# accomplishes this feature using checked and unchecked statements. This article illustrates on these statements with simple examples.

When can the Overflow occur? Overflow can occur during the following cases:

• When you perform conversions by explicitly casting integral types or enum types
• When you use the operators ++, --, +, -, *, / and frame an expression on integral types or enum types
• When you use the operator unary - to frame an expression on integral types

What is an Overflow? You perform a computation in your code using any of the operators mentioned above and assign the computation result to a variable of specific type. If the result value is too large to fit into the resultant variable of specified type, then overflow is said to occur. Here is a simple example:

class sampleClass {
public static void Main() {
int var1 = 2147483647;
int var2 = 10;
int var3 = (int) var1 + var2;
Console.WriteLine(“Output of 2147483647+ 10 = {0}”, var3);
}
}

Output of this code will be:

Output of 2147483647+ 10 = -2147483639

Is this the expected output? NO. But it has occurred because the maximum value that an integer can hold is 2147483647. When you add an integer value 10 to value 2147483647, expected output is 2147483657. But an integer variable cannot hold this value. This is meant as overflow. The above example doesn’t handle overflow explicitly. Hence the default behavior of overflow occurrence results in the above shown output.

What are the Different Ways of Handling Overflow? Certain values and transactions might end up in overflow because of the data passed by User or due to internal manipulations. You cannot avoid overflow in all cases by specifying the largest data type to hold data. But you can handle overflow. Overflow can be handled in four different ways in C#:

• Using Checked Statement: Checked Statement will enclose a block of code. If any overflow occurs in that block of code, then there are two possible results:

o If the variables involved in the overflow are constants then compile time error will occur
o If not, then the overflow will be determined only during runtime and you will end up in OverflowException

• Using Unchecked Statement: If you should not handle overflow for a specific block of code, then you specify them inside unchecked statement. When an overflow occurs inside unchecked block, no error will be thrown. Instead the result will be truncated to fit into the resultant type.

• Setting Compiler Option: While compiling the code, you can set \checked option. If you do so, your entire file content will be checked for overflow. If there any overflow occurrences, then the result will be similar to usage of checked statement. However if you have any unchecked statements in your code the compiler will skip the block of code inside unchecked block and check for overflow in rest of the code.

• Do Not Handle Explicitly: If you do not specify checked or unchecked statements in your code and you do not specify \checked option while compiling the file, default behavior will be triggered

Last two options are straight forward. In rest of the article, you will deal with the first two options.

Consider the following example containing unchecked statement:

class sampleClass {
public static void Main() {
const int var1 = 2147483647;
const int var2 = 10;
unchecked {
int var3 = (int) var1 + var2;
Console.WriteLine(“Output of 2147483647+ 10 = {0}”, var3);
}
}
}

Output of this code will be:

Output of 2147483647+ 10 = -2147483639

Now, you enclose the code inside checked statement instead of unchecked statement :

class sampleClass {
public static void Main() {
const int var1 = 2147483647;
const int var2 = 10;
checked {
int var3 = (int) var1 + var2;
Console.WriteLine(“Output of 2147483647+ 10 = {0}”, var3);
}
}
}

Output of this code will be:

Compiler error stating “The operation overflows at compile time in checked mode.” will occur

If you try the same example without specifying the integers as constants, then you will end up in runtime exception as shown below:

class sampleClass {
public static void Main() {
int var1 = 2147483647;
int var2 = 10;
try {
int var3 = checked((int) var1 + var2);
Console.WriteLine(“Output of 2147483647+ 10 = {0}”, var3);
}
catch(System.OverflowException exp) {
Console.WriteLine(“ Runtime Exception Occurred : “ + exp.ToString());
}

}
}

Output of this code will be:

Runtime Exception Occurred : System.OverflowException: Arithmetic operation resulted in an overflow.

Note that as shown in the above example, you can use checked statement to cover a single statement instead of block of code. Even unchecked statement can wrap a single statement or expression.

_______________________________________________________________________

Add to My Yahoo!


FREE Subscription

Subscribe to our mailing list and receive new articles
through email. Keep yourself updated with latest
developments in the industry.

Name:
Email:

Note : We never rent, trade, or sell my email lists to
anyone. We assure that your privacy is respected
and protected.

Visit .NET Programming Tutorial Homepage

______________________________________________________

Recommended Resource

| .NET 3.5 Framework – New Features and Benefits | Overview of .NET Framework 3.5 Architecture | Overview of Unary Operators of C# (C Sharp) | Understanding of Checked and Unchecked Statement Type of C# (C Sharp) | Understanding of fixed Statement in C# (C Sharp) | Understanding of lock Statement in C# (C Sharp) | Understanding of Logical Operators (Bitwise, Boolean) in C# (C Sharp) | Understanding of Logical Operators (Conditional) in C# (C Sharp) |


| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2017 - All Rights Reserved.