Lali

Lali

  • NA
  • 12
  • 0

Object reference not set to an instance of an object run-time error

Dec 27 2009 2:28 AM

I am new to C# but experienced in C++.  I have been strugling with the "Object reference not set to an instance of an object" run-time error when accessing array elements in the example below. The error is reported in Main when assigning 100 to myItemList.item[0].somedata (shown in red). Any help would be appreciated. Thx.
namespace ConsoleApplication1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    public class Item
    {
        public Item()
        {
            someData = 0;
        }
        public int someData;
    }
    public class ItemList
    {
        public ItemList()
        {
            itemCount = 0;
        }
        public ItemList(int count)
        {
            itemCount = count;
            items = new Item[count];
        }
        public int itemCount;
        public Item[] items;
    }
    class Program
    {
        static void Main(string[] args)
        {
            ItemList myItemList = new ItemList(2);
            myItemList.items[0].someData = 100;
        }
    }
}

 

Answers (7)