Assigning Value to a variable that is too big for it! (checked and unchecked concept)
So when we assign a value to a variable then that variable should be able to hold开发者_高级运维 it, right? and if not compiler produces the error. Now there is an option in C# known as Checked (which is by default) and unchecked option. But is there practical use of unchecked? any comments for a layman? :)
Example:
int a=int.MaxValue;
int b=int.MaxValue;
unchecked
{
int sum=a+b;
}
The practical use of unchecked is that it's faster.
checked [...] is [...] default
The default for non-constant expressions is unchecked (unless specified otherwise by the compiler or execution environment). It's one of the few times C# chooses performance at the cost of safety. Since the majority of code never gets anywhere near the limits it is rarely an issue in practice.
In addition to the speed issue mentioned by @Mark Byers, I've used unchecked
when computing hash codes for objects - the typical method for creating a hash code from multiple items (for example, object members) is to iteratively multiply your working hash code by some factor, then add the hash code for the new item and repeat. This can produce numbers that would normally overflow an int, but we don't care about the excess, so using unchecked makes the operation possible (and fastish).
Also note that according to the checked article on MSDN, unchecked isn't the default for non-const expressions. In this case, the runtime checking behaviour depends on compiler options and environment configuration. In particular, I've noticed that when building with SharpDevelop in the past, I get the checked behaviour unless I specify something different.
One way I've used it in the past is to express COM error codes as ints. This is handy as the ErrorCode property of the COMException object is an int, but almost all documentation you'll see refers to the 0x800... form
e.g.
const int knownErrorCode = unchecked((int)0x800AC472);
try
{
// Some COM code that could blow up
}
catch (COMException ex)
{
if (ex.ErrorCode == knownErrorCode )
{
// Do stuff
}
}
精彩评论