accidentally at work I wrote the following line of code:
string x = (object) null;
// It was var x = (object)null and I changed from var to string instead of
// object x = null;
This gave me a compilation error similar to this: Can't cast source type object to target type string
Why? Isn't null
just a bunch of zeros pointing to "nowhere" memory address, no matter what the type is?
The question here is basically "why does the compiler not take into account the fact that it knows that the assigned value is a constant reference known to be null?"
The answer is: why should it? What's the compelling benefit of taking that information into account? You deliberately said "I want this expression to be treated as though it were of type object", and you can't assign a value of type object to a variable of type string. What's the benefit of allowing that in this case?
The code seems to me to be highly likely to be a bug; surely the compiler should be telling you about it rather than allowing it.