Cook Computing

Using unchecked Keyword in C#

June 25, 2004 Written by Charles Cook

Just a minor C# issue I came across yesterday. I needed to assign an error code to the protected HResult member of a class derived from the .NET Exception class. The following code does not compile, resulting in an "assigning uint to int" error message and casting won't work and casting to int doesn't work because the value is too large


HResult = 0x80045000;

In a case like this you need to use the unchecked keyword to indicate that you're not bothered about the arithmetic overflow:


HResult = unchecked((int)0x80045000);