Share via


foreach without variable declaration

Question

Tuesday, July 19, 2011 5:26 PM

Hi all,

I am using the foreach construct.  It appears I must define the variable inside the construct ie:

foreach (int foo in bar)
{...}

But in my case, I want to see the value of the last foo outside the loop (say I have a break somewhere in the block).  But apparently, I can't use the following code:

int foo;
foreach (foo in bar) // Note: no declaration for foo
 {...}
console.write( foo);

I know I can simply assign the value of foo to some other variable defined outside the scope (say right before the break), but I was just wondering if this was my only option.  It's not a big deal, just curious.

Thanks

FletcherJ

All replies (6)

Tuesday, July 19, 2011 5:45 PM âś…Answered

This is not allowed with foreach - although it will work with for and while loops.  Foreach requires the variable to be declared as part of the looping construct.

 

This is due to the C# Language spec, section 5.3.3.16, which defines foreach as having the syntax of:

foreach ( type identifier in expr ) embedded-statement

There is no allowance for an identifier to be used which is not defined (with it's type) directly in the foreach statement.  If you want to "store" the value for use beyond the loop, you need to use a separate, second identifier, and copy the value, as sambeet demonstrated.

 

Reed Copsey, Jr. - http://reedcopsey.com
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".


Tuesday, July 19, 2011 5:33 PM | 1 vote

Hi

This is the syntax defined by framework designers....so we need to adhere to syntax....

I guess this is not possible...

If this post answers your question, please click "Mark As Answer". If this post is helpful please click "Mark as Helpful".


Tuesday, July 19, 2011 5:33 PM

You can also use other loops contructs like for or while that gives you more control

Regards


Tuesday, July 19, 2011 5:35 PM

What happens when you declare int foo; outside of the loop? That should be possible and I know I've done it many times.Bob - www.crowcoder.com


Tuesday, July 19, 2011 5:37 PM

While it is not possible due to the syntax rules,you can do this:

int foo1;
foreach (int foo in bar) // Note: no declaration for foo
 {
    foo1 = foo;
 }
console.write(foo1);

 


Tuesday, July 19, 2011 5:38 PM

A working example:

  class Program
  {
    static void Main(string[] args)
    {
      int foo = 0;

      for (foo = 0; foo < 50; foo++)
      {
        Console.WriteLine(foo.ToString());
      }

      Console.WriteLine("The final value of foo is: " + foo.ToString());
      Console.ReadKey();
    }
  }

Bob - www.crowcoder.com