[Mono-list] Simple List problem which is causing me a right royal issue!

Nicholas Frechette zeno490 at gmail.com
Sun Apr 1 22:23:05 UTC 2012


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
<paul at all-the-johnsons.co.uk> 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  -  Mono-list at lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-list


More information about the Mono-list mailing list