9

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

David
  • 15,750
  • 22
  • 90
  • 150

6 Answers6

27

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    and +1 for the field/variable distinction – Blorgbeard May 28 '10 at 13:28
  • When I wrote the question I meant local variable rather than field, but since I was unaware of the distinction in this regard I didn't make that clear. I didn't know that int fields were initialised at zero - thanks for that info. – David May 28 '10 at 14:04
5

default of int is 0

Itay Karo
  • 17,924
  • 4
  • 40
  • 58
5

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

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
2

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.

tpeczek
  • 23,867
  • 3
  • 74
  • 77
2

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.

Ty.
  • 3,888
  • 3
  • 24
  • 31
1

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

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222