Cast null value to a type

UfukSURMEN picture UfukSURMEN · Dec 19, 2016 · Viewed 20.6k times · Source

I have a simple question. if we cast some null variable to a type. I expect compiler to throw Some Exception, but it is not. And I realy want to know the reason why. I mean

string sample1 = null as string;
string sample2 = (string)null;


object t1 = null;
TestClass t2 = (TestClass)t1; 

maybe in the first one, as operator handles the exception handling. But others samples must throw exception. How compiler handles these situations , maybe since the variables are null , it does not perform cast operation? Cause if it really cast a null pointer it must be an error.

Answer

Stephan picture Stephan · Dec 19, 2016

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.

However, if you try string null → TestClass null (Assuming TestClass is not a subtype of string), you will find a compilation error as TestClass is not a derived type of string.