Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast null value to a type

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.

like image 638
yigitt Avatar asked Dec 19 '16 09:12

yigitt


People also ask

Can null be cast to int?

1 Answer. You can cast null to any source type without preparing any exception.

Can null be cast C#?

1 Answer. Show activity on this post. 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.

Can null be cast to Boolean?

Unfortunately the compiler is not capable of deducing that the statement boolean var1=(var=null); would always lead to the invalid assignment boolean var1=null .

Can you cast a null pointer?

There's no "memory assigned" to a pointer. A pointer is just an object containing an address. This might be an address of an actually usable object, or it might be invalid. If it's NULL , it's guaranteed to be invalid.


1 Answers

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.

like image 61
Stephan Avatar answered Oct 23 '22 22:10

Stephan