0

Have few questions related to nullable type:

int x;  
Console.WriteLine(x);

If a variable is not initialized does that means it contain nothing or we can say it is empty. So is this empty value is equivalent to null?

If yes then how a value type object contain a null value? If no, then what is this empty value called?

If I try to compile uninitialized int variable(above mentioned code) then compiler returns me an error use of unassigned local variable but it won't tell me what is stored inside the variable.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Amit Bisht
  • 4,870
  • 14
  • 54
  • 83

3 Answers3

1

Unlike fields, the compiler can easily detect that you are using a local non-initialized variable, and will not let you compile that code, hence there's no value for it.

With fields, the situation is a little bit different as the compiler will not shout, but rather assign the default value for that type. In case of an int it would be 0;

Ofir Winegarten
  • 9,215
  • 2
  • 21
  • 27
0

Java does not allow any code to read an uninitialised variable.

Although the compiler/JVM (Java Virtual Machine) ensures all fields of classes are initialised to 0, 0.0, '\0' or null (as appropriate) it cannot efficiently do that with local variables. Therefore the compiler requires you to set the variable before any possible path allows it to be read.

Naz
  • 76
  • 5
  • I don't believe that's the reason for it not happening with local variables - I believe it's more for the sake of correctness, to avoid bugs... it's more that the compiler can't do that with *fields* so they have to have a default value. – Jon Skeet Mar 19 '17 at 09:55
0

A reference type is stored as a reference (like a pointer) to an object instance. null means a reference that isn't pointing to an instance of an object.

A value type is stored as the value itself, without any references. It doesn't make sense to have a null value type, since by its definition it contains a value.

int is a value type and not a reference type, which means you cannot assign a null to a value type.

You can make a value type nullable in C# and Java (the syntax differs a bit though). The Nullable type has a HasValue flag that tells you whether there's no value (actually there is, but it's the default value of the value type). Usage (C#):

int? NullableInt = null;
Console.WriteLine(NullableInt.Value);

The reason you encounter the error of use of unassigned local variable, is that local valuables aren't initialized by default. Class members are initalized by default for example. They have no value and are not equal to null.

According to this answer, Microsoft could have allowed uninitialized local variables. They simply chose not to, because it would have been a bug and not because it would prevent you from observing the garbage uninitialized state of the local.

Community
  • 1
  • 1
bl4y.
  • 530
  • 1
  • 3
  • 10