The MSDN examples are just compile time errors.
It’s just I see @JonSkeet uses it an answer here: https://stackoverflow.com/a/263416/360211 and I can’t see why if it’s just compile time.
static void Main()
{
const int x = 4;
int y = int.MaxValue;
int z = x*y;
Console.WriteLine(z);
Console.ReadLine();
}
Produces -4, same as this:
static void Main()
{
unchecked
{
const int x = 4;
const int y = int.MaxValue;
int z = x*y; // without unchecked, this is compile error
Console.WriteLine(z);
Console.ReadLine();
}
}
This throws runtime:
static void Main()
{
checked
{
const int x = 4;
int y = int.MaxValue;
int z = x*y; //run time error, can checked be set system wide?
Console.WriteLine(z);
Console.ReadLine();
}
}
So is Jon doing this because it could be set system wide, compiler flag or otherwise?
Whether an operation is in a
checkedoruncheckedblock is executed when the values are actually computed. When multiplying/adding two variables this will almost always be at runtime, since they aren’t known at compile time.In your example the two variables are both constants; this means that the result of the computation between compile time literals can be done at compile time (which it is). Since the result is being computed at compile time, and it’s not in an
uncheckedblock, it can’t compute the result without an error. That does not mean that checked/unchecked blocks are generally a compile time check; they very rarely are.And yes, it is possible to change the project properties for whether the entire code base is in a checked/unchecked context. If you’re writing a library it’s also possible for the method to be called from within either context. For that reason, if there’s a block of code that must run in either a checked or unchecked context it’s a good practice to add such a block, even if your current project setting is correct for that method. Also, if nothing else, it’s making the intent of that snippet clearer to future readers, “This method relies on integer overflow,” vs., “This method must never overflow.”