.net value type initialization

寵の児 提交于 2019-12-23 17:25:31

问题


What is the value in memory of, for example, integer value (int) after declaration but not initialization? In "CLR vi C#" Richter writes, that value types is initialized with 0, but not allowed to be used. So what will be in memory after declaration of variable like this

int testVar;

And how is mechanism of initializing check implemented?


回答1:


Types are initialized with memory that is all zeros. I don't know if this is according to the specification for all value types so you can't count on this unless you check. For different value types zeros in memory can mean different things depending on what the type represents.

Value types are auto initialized and can be used when they are a field of a class and not local variables. As far as I know there is no initialization check in the CLR itself. The initialization check is performed by the compiler and it reports compile time error when uninitialized variable is used.




回答2:


As far as I know, the declaration reserves some memory according to how may bytes this specific type needs. These bytes could in theory be randomly filled with whatever was physically occupying those specific bytes of hardware.




回答3:


In c#, some types allow you to have variables that can have a null value, like Nullable variables (Int32? intAux). This type will be null, at first. Otherwise, Int32 variables do not allow that you have null values.

And you can verify if a variable was initialized or wasn't, doing something like (intAux == null).



来源:https://stackoverflow.com/questions/9567726/net-value-type-initialization

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