Should variable declarations always be placed outside of a loop?

前端 未结 6 1411
伪装坚强ぢ
伪装坚强ぢ 2020-12-20 15:39

Is it better to declare a variable used in a loop outside of the loop rather then inside? Sometimes I see examples where a variable is declared inside the loop. Does this ef

6条回答
  •  鱼传尺愫
    2020-12-20 15:51

    I am going to agree with most of these other answers with a caveat.

    If you are using lambada expressions you must be careful with capturing variables.

    static void Main(string[] args)
    {
        var a = Enumerable.Range(1, 3);
        var b = a.GetEnumerator();
        int x;
        while(b.MoveNext())
        {
            x = b.Current;
            Task.Factory.StartNew(() => Console.WriteLine(x));
        }
        Console.ReadLine();
    }
    

    will give the result

    3
    3
    3
    

    Where

    static void Main(string[] args)
    {
        var a = Enumerable.Range(1, 3);
        var b = a.GetEnumerator();
        while(b.MoveNext())
        {
            int x = b.Current;
            Task.Factory.StartNew(() => Console.WriteLine(x));
        }
        Console.ReadLine();
    }
    

    will give the result

    1
    2
    3
    

    or some order there of. This is because when the task finally starts it will check the current value of it's reference to x. in the first example all 3 loops pointed at the same reference, where in the second example they all pointed at different references.

提交回复
热议问题