15

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.

1
  • 12
    Fields are always automatically initialized to the default value of the field type, which in the case of int is zero. Fields are considered to be definitely assigned; you can read their contents even before an explicit assignment. Locals are not considered to be definitely assigned; you are required to do something which assigns the value of a local before its contents are read. See the "definite assignment" section of the C# specification for details. Commented Jun 4, 2009 at 19:49

8 Answers 8

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

int is a struct not a class. structs have a default value while classes are nul by default.
@Matthew Whited, he didn't mean it was a class. He was saying at the class "level", which really means instance variable. I edited it for clarification.
7

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

3 Comments

But isn't it possible that the ctor for that class handles variable initialization for those variables not explicitly assigned?
Michael: fields are initialized to default (zero) values by the memory manager, not by the constructor.
Many thanks to Eric Lippert for the clarification. I wish I could have given credit to one or more individuals who participated in this discussion. As usual, I always walk away with more knowledge that I came here with ;)
4

Yes, it pretty much is the same thing.

You can refer to this article on Coding Horror

Comments

1

As the following link states, they are exactly the same:

http://msdn.microsoft.com/en-us/library/aa664742%28VS.71%29.aspx

1 Comment

Only true if they are fields (class members). The OP mentions variable and the name also suggests that.
1

With all this talk, it is worth mentioning the "default" keyword in C#.

I.e. int i; is equivalent to int i = default(int); which is equivalent to int i = 0; and MyClass o = default(MyClass); is equivalent to MyClass o = null;

This is especially relevant when using linq methods such as .SingleOrDefault() because you can always use the following to make your code more readable:

int someValue = collection.<various linq methods>.SingleOrDefault();
if (someValue == default(int))
{
  //Code for the default case
}

and

MyClass someValue = collection.<various linq methods>.SingleOrDefault();
if (someValue == default(MyClass))
{
  //Code for the default case
}

Comments

1

Various responses here are kind of misleading, including the referenced article in "Coding Horror" website.

The compiler will optimize your code to remove all "unnecessary" initializations when configured to optimize the generated code. Please notice that this is the default behavior when compiling in "Release" mode.

I, for one, think it's always very useful to initialize all your variables. The performance hit will be minimal in debug mode and none in release mode, but the gains of explicitly set the variables will be tremendous for anyone maintaining the code in the future, in the better "documenting code with code" style. I remember this very experienced coworker of mine that thought that the default value of Int32 was Int32.MinValue instead of 0. These types of confusion always happens to things implicited in the code and, to me, they should be avoided in most cases.

Comments

0

Any time you create a type in C#, it automatically gets filled in with padded zeros. In the case of a class (reference type), this equates to a null pointer. So, technically, any time you're working with classes, the following are identical:

MyClass class;
MyClass class2 = null;

With value types (any struct, including int/float/double/etc), the type is passed with zeros, so the following are equivalent:

int i;
int j = 0;

However, in a method, the compiler checks to see if you've assigned a value to your types prior to using it. If you do the following, the compiler will complain:

int i;
Console.WriteLine{"{0}",i);

Technically, the above should be fine - but since it's a common source of programmer error, the compiler specifically checks for unassigned local variables, and complains. However, this is a compile-time complaint, and not a CLR issue. You can make IL that does the above, and it runs fine.

Comments

0

These are only equivalent for fields (class variables). Fields are automatically assigned the default values when the class is initialized. Within a method or property, the unassigned variable remains unassigned and will cause a compiler error if you try to access it's value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.