Follow in Twitter & Facebook

Like in Facebook

Powered By Blogger Widgets

Free Download

FREE Tools

Tuesday, April 3, 2012

Checked and Unchecked operators in C#

In this article we will discuss what are checked and unchecked operators in C#.Net. You can also see some C#.Net articles. Also you can check Static variables in C#.Net.

We all aware about Stack overflows or OverflowException was unhandled(Arithmetic operation resulted in an overflow).So while doing some arithmatic operation, we sometimes find this type of Exceptions. This is nothing but OverflowException.

Now the question is when exactly it comes ? Overflow happens when the range of a type is exceeded. When a value exceeds the limitations of a data type, it is said to overflow. So at this time these two operators come into the picture.

C# supports two types operators Checked and Unchecked, which can be used for checking and unchecking stack overflows during program execution.

Checked allows you to force C# to raise an exception whenever stack overflow (or underflow) occurs due to type conversion issues.

Unchecked will allow you to ignore these exceptions when the C# project is set to raise these types of exceptions.When using the default C# compiler options, arithmetic is unchecked.
This means that any overflowing data from arithmetic operations is simply truncated.
so finally if an operation is checked then an exception will be thrown if overflows occurs.
If it is not checked ,no exception will be raised but thing is that we will loose the data.

int a = 200000 ;
int b = 300000 ;
int m = checked(a*b) ;
catch(OverflowException e)
since a*b produced a value that will easily exceed the maximum value for an int , an overflow occurs .An overflow exception thrown like this . we will get the output as
System.OverflowException : An exception of type System.OverflowException was thrown at ........

If you want to suppress that overflow hecking , we can mark the code as unchecked .

int a = 200000 ;
int b = 300000 ;
int m = Unchecked(a*b) ;
In this case no exception will raise but we will loose the data. Also check Dataset and Datareader

0 on: "Checked and Unchecked operators in C#"