# List's breaking for loops in c#

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

## 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 on other sites

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 on other sites

Oh right...

List<foo> _foo = new List<foo>();