Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6620027
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T21:02:49+00:00 2026-05-25T21:02:49+00:00

I’m feeling quite confused about the way either C# ‘s foreach and Java ‘s

  • 0

I’m feeling quite confused about the way either C#‘s foreach and Java‘s enhanced for works and even more frustrating is to realize why I haven’t came across this detail before.

But anyway the fact of the matter is, I’d really like to understand why this apparently similar flow control statements work so differently. For illustration purposes let’s assume we need to iterate through an array of integers, with both implementations being something like:

C# 4.0 (code)

class Program
{
    public static void Main(string[] args)
    {
        int[] foobar = new int[] {0, 1, 1, 2, 3, 5, 8, 13, 21};
        Console.WriteLine(String.Format("[DEBUG] type: {0}", foobar.GetType()));
        Console.WriteLine(String.Format("[DEBUG] length: {0}", foobar.Length));
        try
        {
            for (int i = 0; i < foobar.Length; i++)
            {
                Console.Write(String.Format("{0} ", foobar[i]));
            }
            Console.Write(Environment.NewLine);

            foreach (var i in foobar) {
                Console.Write(String.Format("{0} ", foobar[i]));
            }
        }
        catch (Exception exception)
        {
            Console.Write(Environment.NewLine);
            Console.WriteLine(exception.ToString());
        }
        finally
        {
            Console.Write(Environment.NewLine);
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

C# 4.0 (output)

[DEBUG] type: System.Int32[]
[DEBUG] length: 9
0 1 1 2 3 5 8 13 21
0 1 1 1 2 5 21
System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at Dotnet.Samples.Sandbox.Program.Main(String[] args) in e:\My Dropbox\Work\P
rojects\scm\git\sandbox\Dotnet.Samples.Sandbox\Dotnet.Samples.Sandbox\Program.cs
:line 51

Press any key to continue . . .

JAVA SE6 (code)

class Program {
    public static void main(String[] args) {
        int[] foobar = new int[] {0, 1, 1, 2, 3, 5, 8, 13, 21};
        System.out.println("[DEBUG] type: " + (foobar.getClass().isArray() ? "Array " : "") +  foobar.getClass().getComponentType());
        System.out.println("[DEBUG] length: " + foobar.length);
        try {    
            for (int i = 0; i < foobar.length; i++)
            {
                System.out.print(String.format("%d ", foobar[i]));
            }
            System.out.print(System.getProperty("line.separator"));
            for (int i : foobar) {
                System.out.print(String.format("%d ", foobar[i]));
            }
        } catch (Exception e) {
            System.out.print(System.getProperty("line.separator"));
            System.out.println(e.toString());
        }
    }
}

JAVA SE6 (output)

[DEBUG] type: Array int
[DEBUG] length: 9
0 1 1 2 3 5 8 13 21 
0 1 1 1 2 5 21 
java.lang.ArrayIndexOutOfBoundsException: 13
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T21:02:50+00:00Added an answer on May 25, 2026 at 9:02 pm

    In the C# version..

    foreach (var i in foobar)
    {
        Console.Write(String.Format("{0} ", foobar[i]));
    }
    

    ..should be..

    foreach (var i in foobar)
    {
        Console.Write(String.Format("{0} ", i));
    }
    

    Doing a foreach over an array of integers, as you are, does not iterate over array indices: it iterates over the integers.

    Given the array..

    int[] foobar = new int[] {0, 1, 1, 2, 3, 5, 8, 13, 21};
    

    ..your code was:

    Printing element 0: 0
    Printing element 1: 1
    Printing element 1: 1
    Printing element 2: 1
    Printing element 3: 2
    Printing element 5: 5
    Printing element 8: 21
    Printing element 13: IndexOutOfRangeException !!
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have thousands of HTML files to process using Groovy/Java and I need to
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.