views:

83

answers:

6

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

+4  A: 

default of int is 0

Itay
+4  A: 

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
+1  A: 

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
+11  A: 

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 for providing the background mechanics.
RedFilter
and +1 for the field/variable distinction
Blorgbeard
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
A: 

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
A: 

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

klausbyskov