سؤال

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

هل كانت مفيدة؟

المحلول

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top