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?
You can cast null to any source type without preparing any exception. The println method does not throw the null pointer because it first checks whether the object is null or not. If null before it simply prints the string "null". Otherwise, it will call the toString purpose of that object.
According to the documentation (Explicit conversions) you can cast from a base type to a derived type. Since null is a valid value for all reference types, as long as the cast route exists you should be fine. object null → TestClass null works as object is a superclass to all reference types.
In other words, null can be cast to Integer without a problem, but a null integer object cannot be converted to a value of type int.
The problem is not the casting of null
, it's that object
isn't assignable to string
. This works fine
string x = (string)null;
The reason this works if you remove the cast (string x = null
) is laid out in section 2.4.4.6 of the C# Language Specification
The null-literal can be implicitly converted to a reference type or nullable type
The moment you introduce a cast ((object)null
) you no longer have a null literal. Instead you have a value of type object
. It's essentially no different than
object temp = null;
string x = temp;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With