Value of unassigned non-nullable variable (C#)

风流意气都作罢 提交于 2019-11-29 06:58:22

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.

default of int is 0

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

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.

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.

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).

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