Checked and Unchecked Code in C#
Introduction
C# has huge list of
benefits, checked and unchecked code writing is one of them. Lets talk on some
real example.
int
val1 = 2147483647;
int
val2 = val1 + 1;
Console.WriteLine("Value1 is {0}", val1);
Console.WriteLine("Value2 is {0}", val2);
Above
example has a variable val1 which has value 2147483647 which is largest value
of integer. In second line of code, we have val2 and we are trying to add 1 to
existing largest value of integer. Above code will output exactly as following
code:
int
val1 = 2147483647;
int
val2;
unchecked
{
val2 = val1 + 1;
}
Console.WriteLine("Value1 is {0}", val1);
Console.WriteLine("Value2 is {0}", val2);
In
above both terms C# rolls the value if integer range exceeds so, we are getting
output as following.
Actually
adding 1 in 2147483647 should be 2147483648 but our value is rolling because it
exceeding the integer range.
So,
here if you do wish to have checked use the following code.
int
val1 = 2147483647;
int
val2;
checked
{
val2 = val1 + 1;
}
Console.WriteLine("Value1 is {0}", val1);
Console.WriteLine("Value2 is {0}", val2);
Console.ReadKey();
Now,
if you run above code will produce a OverflowException.
So,
remember if you are working on arithmetical calculation like project, you
should use checked statements for accuracy.
Conclusion
That
is all about checked and unchecked codes in C#. I hope you like this. Please
send you feedback.
Comments
Post a Comment