How do I use foreach to iterate array?

Category: Introduction, viewed: 3K time(s).

This examples displays how to use foreach statement to iterate array items. During the foreach iteration you should not add or remove elements from the collection to avoid unpredictable behaviour.

Inside the foreach statement we can use the break statement to break out from the loop or continue statement to step to the next iteration in the loop.

using System;

namespace Kodecsharp.Example.Intro
{
    class ForeachDemo
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Argument size: " + args.Length);

            foreach (string arg in args)
            {
                Console.WriteLine("Argument: " + arg);
            }
        }
    }
}
Powered by Disqus