CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: List and Arrays

  1. #1
    Join Date
    Jun 2010
    Posts
    56

    List and Arrays

    This might be a silly question but how do you properly compensate for List Counts and Array Size?

    For example Lists and Array start at 0, but if I want to loop through them I need to -1 off the Count/Length or else I will get an out of bounds condition, is this a proper way of coding?

    You can see my code below.

    Code:
                List<string> introMessage = new List<string>();
    
                using (StreamReader introRead = new StreamReader("intro.txt"))
                {
                    string line;
                    while ((line = introRead.ReadLine()) != null)
                    {
                        introMessage.Add(line);
                    }
                }
                for (int x = 0; x <= introMessage.Count-1; x++)
                {
                    Console.WriteLine(introMessage[x]);
                }

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: List and Arrays

    No, you are doing it wrong (well, maybe not wrong. It does work, it is just unconventional and unnecessary). You are using <=, when you need only use <.

    Code:
    for( int i = 0; i < someArray.Length; ++i )
    {
        // do stuff
    }
    However, arrays and generic collections implement IEnumerable, so just use a foreach statement instead:

    Code:
    foreach( int i in someArrayOfInts )
    {
        // do stuff
    }
    Last edited by BigEd781; July 8th, 2010 at 03:30 PM.

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: List and Arrays

    As Ed mentioned...

    Code:
    for (int x = 0; x < introMessage.Count; x++)
    {
      Console.WriteLine(introMessage[x]);
    }
    or using foreach...

    Code:
    foreach ( var line in introMessage )
    {
      Console.WriteLine( line );
    }
    In general, prefer using foreach over for.

  4. #4
    Join Date
    Jun 2010
    Posts
    56

    Re: List and Arrays

    I didn't know about foreach but I am definitely using that from now on.

    Once again excellent responses from this forum.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured