Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Variable Initialization Question

Is there any difference on whether I initialize an integer variable like:

int i = 0;
int i;

Does the compiler or CLR treat this as the same thing? IIRC, I think they're both treated as the same thing, but I can't seem to find the article.

like image 795
coson Avatar asked Jun 04 '09 19:06

coson


2 Answers

If the variable i is an instance variable, it will be assigned the value 0 automatically. If it is a local variable in a method, it is undefined, so you would need to assign it a value before using it.

For example:

class Program
{
    static void Main(string[] args)
    {
        intTest it;

        it = new intTest();

        Console.ReadLine();
    }

    class intTest
    {
        int i;

        public intTest()
        {
            int i2;

            Console.WriteLine("i = " + i);
            Console.WriteLine("i2 = " + i2);
        }
    }
}

The above will not compile because i2 is unassigned. However, by assigning 0 to i2, i.e.

int i2 = 0;

and compiling, then running, will show that both are now assigned 0.

like image 86
Michael Todd Avatar answered Sep 30 '22 01:09

Michael Todd


I looked at the IL (using ildasm) and its true that only the int set to 0 is really set to 0 in the constructor.

public class Class1
{
    int setToZero = 0;
    int notSet;
}

Generates:

.method public hidebysig specialname rtspecialname 
        instance void  .ctor() cil managed
{
  // Code size       15 (0xf)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldc.i4.0
  IL_0002:  stfld      int32 ClassLibrary1.Class1::setToZero
  IL_0007:  ldarg.0
  IL_0008:  call       instance void [mscorlib]System.Object::.ctor()
  IL_000d:  nop
  IL_000e:  ret
} // end of method Class1::.ctor
like image 31
TheSean Avatar answered Sep 30 '22 00:09

TheSean