Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting null doesn't compile

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?

like image 637
gdoron is supporting Monica Avatar asked Jan 25 '12 18:01

gdoron is supporting Monica


People also ask

What happens if you cast a null?

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.

Can you cast a null C#?

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.

What happens when you cast null to INT?

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.


1 Answers

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;
like image 77
JaredPar Avatar answered Sep 18 '22 06:09

JaredPar