Microsoft .NET Interviewfragen und Antworten
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 } |
Zum Wiederholen speichern
Speichere diesen Eintrag als Lesezeichen, markiere ihn als schwierig oder lege ihn in einem Wiederholungsset ab.
Melde dich an, um Lesezeichen, schwierige Fragen und Wiederholungssets zu speichern.
Ist das hilfreich? Ja Nein
Am hilfreichsten laut Nutzern:
- Name 10 C# keywords.
- What is public accessibility?
- .NET Stands for?
- What is private accessibility?
- What is protected accessibility?