Cast null value to a type

你离开我真会死。 提交于 2019-12-06 17:21:57

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/41219501/cast-null-value-to-a-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!