Follow on Google News News By Tag Industry News * C# Programming * More Industries... News By Place Country(s) Industry News
Follow on Google News | How to use Checked and Unchecked statement in C#.Checked and unchecked statement checks the integral-type arithmetic overflow exception. If you want to ignore arithmetic overflow exception then you can write you code under the unchecked block. By default C# takes arithmetic operation as checked.
By: Steven Clark What is arithmetic overflow exception? Before understanding checked and unchecked statement you must know what is arithmetic overflow exception? Each data type can store limit amount of data. For example, an integer type variable can store data up to 32 bit and ranging from -2,147,483,648 to 2,147,483,647. If in runtime or compile time the integer variable encounters larger number that is outside from its boundary, it raises exception. If variable is defined with unchecked statement then it doesn’t return exception and shows incorrect output. What is Checked and Unchecked statement? The checked and unchecked is a way to check output value whether it is outside of range or not. If you want to ignore arithmetic overflow exception then you can use unchecked statement block to write code. In this situation, the variable will produce the appropriate output that might be different from correct output. If you want to check each value strongly then you can write code within checked statement. It will strictly check the value and then store in a variable. If any overflow encounters, it raises exception in runtime as well as compile time. What if we don’t use any statement? Fortunately, C sharp is type safety language so it takes checked statement by default. If you don’t use any of the statement, then C sharp marks the code as checked and returns exception if overflow rises. How to use checked and unchecked statement in C# program? It is very easy to use checked and unchecked in program. Just put your code in the checked or unchecked block as follow: using System; namespace checked_and_ { class Program { static void Main(string[] { int num = 0; num = Int32.MaxValue; try { Console.WriteLine("\ unchecked { num = num + 1; Console.WriteLine( } num = Int32.MaxValue; Console.WriteLine("\ checked { num = num + 1; Console.WriteLine( } } catch (ArithmeticException ex) { Console.WriteLine( } Console.ReadLine(); } } } In the preceding example an integer variable num is assinged with its maximum value. After that we increment it by one in unchecked block and it returns incorrect output as -2147483648. Again we test same code in checked block and it returns System.OverflowException. You can learn complete details about checked and unchecked statement in the following C# Tutorial. For more info about C# xor operator, please visit to: http://www.completecsharptutorial.com End
Account Email Address Account Phone Number Disclaimer Report Abuse
|
|