Value of unassigned non-nullable variable (C#)

烈酒焚心 提交于 2019-11-28 00:37:22

问题


Just curious.

If you go:

string myString;

Its value is null.

But if you go:

int myInt;

What is the value of this variable in C#?

Thanks

David


回答1:


Firstly, note that this is only applicable for fields, not local variables - those can't be read until they've been assigned, at least within C#. In fact the CLR initializes stack frames to 0 if you have an appropriate flag set - which I believe it is by default. It's rarely observable though - you have to go through some grotty hacks.

The default value of int is 0 - and for any type, it's essentially the value represented by a bit pattern full of zeroes. For a value type this is the equivalent of calling the parameterless constructor, and for a reference type this is null.

Basically the CLR wipes the memory clean with zeroes.

This is also the value given by default(SomeType) for any type.




回答2:


default of int is 0




回答3:


The default value for int is 0.

See here for the full list of default values per type: http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx




回答4:


Here is a table of default values for value types in C#: http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx Reference types default value is usually null.




回答5:


String is a reference type. Int is a value type. Reference types are simply a pointer on the stack directed at the heap, which may or may not contain a value. A value type is just the value on the stack, but it must always be set to something.




回答6:


The value for an unitialized variable of type T is always default(T). For all reference types this is null, and for the value types see the link that @Blorgbeard posted (or write some code to check it).



来源:https://stackoverflow.com/questions/2929257/value-of-unassigned-non-nullable-variable-c

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