Cast operators do not obey the distributive law

Another interesting question from StackOverflow. Consider the following unfortunate situation: object result;bool isDecimal = GetAmount(out result);decimal amount = (decimal)(isDecimal ? result : 0); The developer who wrote this code was quite surprised to discover that it compiles and then throws “invalid cast exception” if the alternative branch is taken. Anyone see why? In regular algebra,…

23

Type inference woes, part two

So what’s the big deal anyway? The difference between the spec and the implementation is subtle, only affects a few specific and rather unlikely scenarios, and can always be worked around by inserting casts if you need to. Fixing the implementation would be a breaking change, it seems like a small and simple change to…

2

Type inference woes, part one

The C# compiler has a subtle violation of the specification which raises an interesting question for some of the new LINQ-related features. The specification for the ?: operator states the following: The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of…

7