Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declare variable outside of the foreach loop

Tags:

c#

.net

In for loop case I can declare the index outside the for statement. For example, instead of

for (int i = 0; i < 8; i++) { }

I can do:

int i;
for (i = 0; i < 8; i++) { }

Now in compare to foreach loop, I have to declare the variable inside the loop:

foreach (string name in names) { }

And I cannot do something like:

string name;
foreach (name in names) { }

The reason this bothers me is that after the loop I want to use the variable "name" again. In case of foreach loop the variable "name" can't be used since it outside of the foreach scope, and I cannot declare another variable with the same name since it declared before in the same scope.

Any idea?

like image 833
Naor Avatar asked Aug 16 '11 09:08

Naor


People also ask

How do you use a variable outside of a loop?

SOLUTION: What you have to do to use a variable outside a loop, is to declare it before the loop begins, you don't have to initialize the variable before, but you have to initialize it before you try to use it for anything.

Should variables be declared outside of loop?

Nowadays, it does not matter. The compiler will perform several optimizations and the final code will be equivalent. There is a best practice that says the scope of local variables should always be the smallest possible. In this case, it's better to declare your variable inside the loop.

What is VAR in foreach loop?

Infer the foreach loop variable type automatically with var The foreach loop is an elegant way to loop through a collection. With this loop we first define a loop variable. C# then automatically sets that variable to each element of the collection we loop over. That saves some of the hassles that other loops have.


1 Answers

Well, you can do:

string name = null; // You need to set a value in case the collection is empty
foreach (string loopName in names)
{
    name = loopName;
    // other stuff
}

Or more likely:

string name = null; // You need to set a value in case the collection is empty
foreach (string loopName in names)
{
    if (someCondition.IsTrueFor(loopName)
    {
        name = loopName;
        break;
    }
}

If the contents of the foreach loop is just to find a matching element - which at least sounds likely - then you should consider whether LINQ would be a better match:

string name = names.Where(x => x.StartsWith("Fred"))
                   .FirstOrDefault();

Using LINQ can often make code which is basically trying to find something a lot simpler to read.

like image 95
Jon Skeet Avatar answered Nov 06 '22 11:11

Jon Skeet