Is it better coding practice to define variables outside a foreach even though more verbose?

前端 未结 12 2257
栀梦
栀梦 2020-12-10 10:39

In the following examples:

  • the first seems more verbose but less wasteful of resources
  • the second is less verbose bu
12条回答
  •  孤街浪徒
    2020-12-10 11:15

    The second form is no more wasteful - it's simply better.

    There's no advantage to declaring the variables outside the loop, unless you want to maintain their values between iterations.

    (Note that usually this makes no behavioural difference, but that's not true if the variables are being captured by a lambda expression or anonymous method.)

提交回复
热议问题