Question: What is checked { } and unchecked { }?Answer: By default C# does not check for overflow (unless using constants), we can usechecked to raise an exception. E.g.: static short x = 32767; // Max short value static short y = 32767; // Using a checked expression public static int myMethodCh() { int z = 0; try { z = checked((short)(x + y)); //z = (short)(x + y); } catch (System.OverflowException e) { System.Console.WriteLine(e.ToString()); } return z; // Throws the exception OverflowException } This code will raise an exception, if we remove unchecked as in: //z = checked((short)(x + y)); z = (short)(x + y); Then the cast will raise no overflow exception and z will be assigned –2. unchecked can be used in the opposite way, to say avoid compile time errors with constanst overflow. E.g. the following will cause a compiler error: const short x = 32767; // Max short value const short y = 32767; public static int myMethodUnch() { int z = (short)(x + y); return z; // Returns -2 } The following will not: const short x = 32767; // Max short value const short y = 32767; public static int myMethodUnch() { int z = unchecked((short)(x + y)); return z; // Returns -2 } |
Is it helpful?
Yes
No
Most helpful rated by users:
- Name 10 C# keywords.
- What is public accessibility?
- .NET Stands for?
- What is private accessibility?
- What is protected accessibility?