Although the answer of @DMG solves the problem and is totally correct, it does not explain it, that's why my answer tries to expand the information on the subject a bit.
It is necessary to differentiate between local and instance variable. An instance variable is the one that is defined at the class level. The local variable is defined at the method level.
In the question that concerns us, this difference is important, since in the case of int
for example, if it is an instance variable, it is initialized to its default value, which in the case of int
is 0, however if it is a local variable, its value is undefined. For example, let's see this code:
class prueba
{
int i;
public void metodo()
{
int j;
Console.WriteLine(i);
Console.WriteLine(j);
}
}
This will not compile, since it will complain that the local variable j
is not assigned. However, if we put int j = 0;
, it will compile correctly and Console.WriteLine(i);
will write a 0
, showing that the instance variable has been initialized automatically.