32

If we cast some null variable to a type, I expect the compiler to throw some exception, but it doesn't. Why?

I mean

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


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

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

Pang
  • 9,564
  • 146
  • 81
  • 122
yigitt
  • 778
  • 3
  • 9
  • 16
  • 11
    I don't see the issue here, all of these types (most likely is the case of TestClass) are nullable and so would be able to be cast – Alfie Goodacre Dec 19 '16 at 09:34
  • 2
    +1 @AlfieGoodacre as long as a cast is being made to a reference-type (`class`) and not a value-type (`struct`). Then you should be all fine. – mausworks Dec 19 '16 at 09:37
  • string can be assigned null i.e string str = null; – FaizanHussainRabbani Dec 19 '16 at 09:45
  • So the point I miss is That , If cast is being made to reference type , even the value is null , cast will succeed and return null. – yigitt Dec 19 '16 at 09:47
  • 3
    Also suppose that you have two overloads `MyMethod(Foo foo)` and `MyMethod(Bar bar)` and want to pass a `null` on the first one. How would you do it? `MyMethod((Foo)null)` or `MyMethod(null as Foo)`. – GDS Dec 19 '16 at 10:15
  • @GDS the thing you mentioned, is some good point on the need of null casting. So then the null pointer has some identifier with type in stack. That differentiates it from simple null from type casted null? – yigitt Dec 19 '16 at 10:37
  • 3
    Check Eric Lippert's answer in this question http://stackoverflow.com/a/3652872/1587082 for how null works. – GDS Dec 19 '16 at 10:43

1 Answers1

38

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Stephan
  • 591
  • 4
  • 7