• Advertisement
Sign in to follow this  

List's breaking for loops in c#

This topic is 1150 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

G'day,

I have a bit of an issue at the moment. Maybe I'm not so up with latest iterations of c#...

 

Basically, I try to create list of class in this case called foo.
 
It seems when I try to add items to the loop seems to break. 
 
In this case as an example, whenever int i and j from the for loops get added the loops break. If you put some breakpoints in visual studio you see it doesn't iterate, however once you take it out it does.
 
Basically whenever I try to run this or programs like it I get the same problem.
 
What could be the problem?
 
 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        List<foo> _foo;
        private void Form1_Load(object sender, EventArgs e)
        {
            for (int i = 0; i <= 30; i++)
            {
               for (int j = 0; j<=30; j++)
               {
                   _foo.Add(new foo(i, j)); //This always breaks the loop and the i and j no longer iterate.
               }
            }
        }
    }
    public class foo
    {
        int x, y;
        public foo(int _i,int _j)
        {
            x = _i;
            y = _j;
 
        }
    }

 

Below I have a full copy of the c# code in a text file... not too much difference it seems:

Share this post


Link to post
Share on other sites
Advertisement

You actually need to create the list before using it, otherwise it's just left null and you'll get a null reference exception on the first foo.Add() call (stopping the execution of the loop). Some info here: http://www.dotnetperls.com/list

Edited by Bacterius

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement