问题
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