I believe that their main reason was portability of programs targeting CLR. If they were to allow a type as basic as int
to be platform-dependent, making portable programs for CLR would become a lot more difficult. Proliferation of typedef
-ed integral types in platform-neutral C/C++ code to cover the use of built-in int
is an indirect hint as to why the designers of CLR decided on making built-in types platform-independent. Discrepancies like that are a big inhibitor to the "write once, run anywhere" goal of execution systems based on VMs.
Edit More often than not, the size of an int
plays into your code implicitly through bit operations, rather than through arithmetics (after all, what could possibly go wrong with the i++
, right?) But the errors are usually more subtle. Consider an example below:
const int MaxItem = 20;
var item = new MyItem[MaxItem];
for (int mask = 1 ; mask != (1<<MaxItem) ; mask++) {
var combination = new HashSet<MyItem>();
for (int i = 0 ; i != MaxItem ; i++) {
if ((mask & (1<<i)) != 0) {
combination.Add(item[i]);
}
}
ProcessCombination(combination);
}
This code computes and processes all combinations of 20 items. As you can tell, the code fails miserably on a system with 16-bit int
, but works fine with ints of 32 or 64 bits.
Unsafe code would provide another source of headache: when the int
is fixed at some size (say, 32) code that allocates 4 times the number of bytes as the number of ints that it needs to marshal would work, even though it is technically incorrect to use 4 in place of sizeof(int)
. Moreover, this technically incorrect code would remain portable!
Ultimately, small things like that play heavily into the perception of platform as "good" or "bad". Users of .NET programs do not care that a program crashes because its programmer made a non-portable mistake, or the CLR is buggy. This is similar to the way the early Windows were widely perceived as non-stable due to poor quality of drivers. To most users, a crash is just another .NET program crash, not a programmers' issue. Therefore is is good for perception of the ".NET ecosystem" to make the standard as forgiving as possible.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…