Casting null doesn't compile

2019-06-16 17:10发布

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?

7条回答
唯我独甜
2楼-- · 2019-06-16 17:39

Every class has, a list of definitions for:

Constructors
Destructors
Fields
Methods
Properties
Indexers
Delegates
Events
Nested Classes

Object is a generic type, because every class is inherit from it but not the other way. Those definitions are not the same for every class, so your compiler can decide which types you can assign/cast to each other.

Then you doing: string x = (object)null;

Compiler doesn't care that value you are trying to assign to your x in first place, but it's checks the type definitions of string and just don't let you to shoot your own leg, and generates an error, because it's a type mismatch.

查看更多
登录 后发表回答