Reputation: 34840
This compiles
var fourGb = (long)4*1024*1024*1024;
But this fails
var fourGb = 4*1024*1024*1024;
With "The operation overflows at compile time in checked mode".
So if the compiler knows this will be an overflow why cant it infer that the variable type should be a long?
Upvotes: 3
Views: 165
Reputation: 39277
See http://msdn.microsoft.com/en-us/library/ctetwysk%28VS.80%29.aspx
You asked it to multiply a bunch of ints so the answer is an int according to the C# syntax. Use 'L' if you want a long.
var fourGb = 4L * 1024 * 1024 * 1024;
Upvotes: 5
Reputation: 9698
I don't think it's a good idea to infer the type of variable by the calculation result.
Upvotes: 2
Reputation: 941635
Imagine the uproar that would cause. "But the compiler can figure out an expression should be evaluated as long, why can't the runtime do it?"
And that's not going to happen, way too expensive.
It is essential that the compiler evaluates expressions the same way as the runtime. If that wasn't the case, editing a constant expression and replacing a constant with a variable could suddenly cause runtime failure. Hard to diagnose failure at that, non-constant expressions are unchecked by default.
Upvotes: 2
Reputation: 432311
It's the same in most languages:
Any other behaviour would give unintended consequences
Arguably you've :
double varname = 1/2
Upvotes: 0