-2

This code is working.

public class Hello{
    public static void Main(){
    int a = 1;
    int[] i = new int[]{1,2,3};
    foreach(int n in i)
    {
        a = n;
    }
    System.Console.WriteLine(a);
    }
}

This code is good too.

public class Hello{
    public static void Main(){
    int a ;
    int[] i = new int[]{1,2,3};
    System.Console.WriteLine(a);
    }
}

Although, next code is not working. Compiler says "Use of unassigned local variable `a'".

public class Hello{
    public static void Main(){
    int a ;
    int[] i = new int[]{1,2,3};
    foreach(int n in i)
    {
        a = n;
    }
    System.Console.WriteLine(a);
    }
}

Why is this code bad?

  • 5
    You are incorrect. Your second version is also going to throw the same compiler error. – David L Sep 09 '16 at 15:21
  • The compiler won´t evaluate *if* the loop might get executed. It simply uses the easieast assumption that it is possible that your loop won´t execute at all. – MakePeaceGreatAgain Sep 09 '16 at 15:21
  • [Please check](https://dotnetfiddle.net/wWZcAM) – huse.ckr Sep 09 '16 at 15:21
  • Type `int` is a structural type and as any other `struct`s must be fully initialized before it can be used. If compiler thinks that there is no guarantee that this type *is* initialized, it throws. – Fabjan Sep 09 '16 at 15:22

4 Answers4

1

Because compiler doesn't know if there are any elements in i variable. If there aren't any then a will stay unassigned.

MistyK
  • 6,055
  • 2
  • 42
  • 76
  • If `a` was initially assigned as `int a = 0`, `int? a = null`, or `int a = default(int)` then you'd be fine, but who knows what to write to the console if the value isn't set. – KSib Sep 09 '16 at 15:25
0

The array i could be empty (from the compiler perspective), although we now from the declaration that i contains some elements. But I assume that the compiler "thinks" that the foreach-loop might be not executed and therefore there is the possibility that a will not be assigned by all code paths.

By the way - the second example has got the same problem:

public class Hello{
    public static void Main(){
        int a ;   // <= not assigened either
        int[] i = new int[]{1,2,3};
        System.Console.WriteLine(a);
    }
}
Ralf Bönning
  • 14,515
  • 5
  • 49
  • 67
0

Because the compiler has no way of knowing whether i contains any element at all. If i is an empty array then a will be unassigned.

Steve
  • 11,696
  • 7
  • 43
  • 81
0

The compiler isn't smart enough to know that the line a = n; is guaranteed to run at least once. You know that that line will run, because it's inside of a foreach-loop which loops over a non-empty collection. But the compiler doesn't know this.

Since the compiler doesn't know that the line a = n; will run, it thinks that the variable a may be unassigned at the time that you do System.Console.WriteLine(a). So it gives you an error message.

Tanner Swett
  • 3,241
  • 1
  • 26
  • 32