Introduction
In this blog, we will learn what the uses of checked and unchecked keywords in C# are.
Checked - This is the keyword and a code marker in C# laguage. It means in some of the cases, C# compiler doesn’t care about the code exception because of the default behavior and ignores the unexpected code without throwing an error.
Let’s see what I am trying to explain in a real situation.
- int a = Int32.MaxValue;
- int b = Int32.MaxValue;
Now, I want to add this into some other variable, as shown below.
Suppose int can take 2,147,483,647. This limits the value only, so how can we add two maximum values into a variable?
Thus, we have the checked keyword. To force the compiler, check the code and raise the overflow exception.
Let’s see the concept in the code.
- using System;
- namespace mathfunction {
- public class csharpdemo {
- public static void Main() {
- int a = Int32.MaxValue;
- int b = Int32.MaxValue;
- int c = a + b;
- Console.WriteLine("The sum of a+b is :" + c);
- Console.Read();
- }
- }
- }
Output
Thus decorate the a+b into checked keyword, as shown below.
Now, you can see the result here. We are getting the proper exception through checked keyword.
Unchecked - Unchecked is also a code marker but it works in some special cases. This is useful in some static or fixed value.
Let’s see the example of the same code.
- using System;
- namespace mathfunction {
- public class csharpdemo {
- public static void Main() {
- const int a = Int32.MaxValue;
- const int b = Int32.MaxValue;
- int c = checked(a + b);
- Console.WriteLine("The sum of a+b is :" + c);
- Console.Read();
- }
- }
- }
In order to ignore these kind of errors, it can use the unchecked keyword. Let’s see the example.
- int c = unchecked( a + b);
Thus, let's conclude this article in short.
- Checked
This is a keyword and code marker to force compiler to check the unexpected code used in program.
- Unchecked
This is a keyword and code marker and to force compiler to ignore the unexpected code or the data type used in the program .
I hope, this article will be useful for you guys. Thanks for your time and patientce for reading this article .
Your comments and feedback are always welcome.