Arrays in C#/.net don't allocate new elements for you when you access an index outside the range of the list. To add new elements, you must first allocate them and then Add them. Only once it has been added to the list can you access them.
ie: var list = new List<vars>(); // list is empty here, access with any index will fail with an exception list.Add(new vars()); // Allocate an instance and add it to the list // list is size 1 here list[0].foo = "bar"; // This is safe here because we added 1 element manually, any other index will fail with an exception Cheers, Nicholas On Sun, Apr 1, 2012 at 5:58 PM, Paul Johnson <[email protected]> wrote: > Hi, > > This is probably something seriously simple to solve, but my brain is > telling me otherwise. > > My code is as follows > > using System; > using System.Collections.Generic; > > namespace ListProblems > { > internal class Program > { > public class vars > { > public string foo; > public string bar; > public int a; > public bool b; > public char c; > public double d; > } > > private static void Main(string[] args) > { > var c = new List<vars>(); > c[0].foo = "hello"; // dies - index out of bounds > Console.WriteLine("c[0] = {0}", c[0].foo); > Console.ReadKey(); > } > } > } > > Problem is really straight forward. How do I add something directly > into c? c.Add() is not going to work as c is a List of class vars. > > Any help would be appreciated here. > > Thanks > > Paul > _______________________________________________ > Mono-list maillist - [email protected] > http://lists.ximian.com/mailman/listinfo/mono-list _______________________________________________ Mono-list maillist - [email protected] http://lists.ximian.com/mailman/listinfo/mono-list
