In C++ there are a lot of ways that you can write code that compiles, but yields undefined behavior (Wikipedia). Is there something similar in C#? Can we write code in C# th
Yes! There is, even in a safe context! (Well, it's implementation defined to be undefined, at least)
Here's one from Marek Safar and VSadov in the Roslyn issues.There is a mismatch between C# and the CLI in regards to bool
.
C# believes that there is only one kind of true
, and one kind of false
.
CLI believes that false
is a byte containing 0, and all other values are true
.
This discrepancy means we can coerce C# to do some a (marginally) interesting things thing:
//non-standard bool
//We're setting a bool's value to a byte value of 5.
var a = new bool[1];
Buffer.SetByte(a, 0, 5);
//non-standard bool
//We're setting a bool's value to a byte value of 10.
var b = new bool[1];
Buffer.SetByte(b, 0, 10);
//Both are true.
Console.WriteLine(a[0]);
Console.WriteLine(b[0]);
//But they are not the same true.
Console.WriteLine(a[0] == b[0]);
The above outputs:
true
true
false
Interestingly, the debugger disagrees (must evaluate truth differently?)
Anyways, the conclusion the C# team appears to have come to is (emphasis added):
I.E. the language will stay entirely unconcerned about nonstandard bools. The particular implementation (as in MS C# on CIL) will acknowledge the existence of nonstandard bools and specify their behavior as undefined