Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of unassigned non-nullable variable (C#)

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

like image 770
David Avatar asked May 28 '10 13:05

David


1 Answers

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.

like image 166
Jon Skeet Avatar answered Oct 19 '22 04:10

Jon Skeet