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?
Every class has, a list of definitions for:
Object is a generic type, because every class is inherit from it but not the other way. Those definitions are not the same for every class, so your compiler can decide which types you can assign/cast to each other.
Then you doing:
string x = (object)null;
Compiler doesn't care that value you are trying to assign to your x in first place, but it's checks the type definitions of string and just don't let you to shoot your own leg, and generates an error, because it's a type mismatch.