PowerShell C# Code Code Code Code C# Code |
Object reference not set to an instance of an object run-time error
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.

Kirtan PatelRank #292 · 8.6K reputationPosted Dec 27, 2009, 6:02 PM EST
Now check it out I corrected the code
if my answer helps you then Check "Do you like this answer" check box please :)
public class Item
{
public int someData;
public Item(int value)
{
someData = value;
}
}
public class ItemList
{
public int itemCount;
public Item[] items;
public ItemList()
{
itemCount = 0;
}
public ItemList(int count)
{
itemCount = count;
items = new Item[count];
}
}
class Program
{
static void Main(string[] args)
{
ItemList x = new ItemList(2);
x.items[0] = new Item(50);
x.items[1] = new Item(100);
Console.WriteLine("Element 1 Data : " + x.items[0].someData.ToString());
Console.WriteLine("Element 2 Data : " + x.items[1].someData.ToString());
Console.ReadKey();
}
}
Kirtan PatelRank #292 · 8.6K reputationPosted Dec 26, 2009, 9:58 PM EST
namespace ConsoleApplication1 using System; using System.Collections.Generic; using System.Linq; using System.Text;namespace ConsoleApplication1 { public class Item { public Item() { someData = 0; }public class ItemList { // It should be Here you have declared it after using it public int itemCount; public Item[] items; public ItemList() { itemCount = 0; }class Program { static void Main(string[] args) { ItemList myItemList = new ItemList(2); myItemList.items[0].someData = 100; } }Lali11 reputationPosted Dec 27, 2009, 2:33 PM EST
theLizardRank #1,079 · 1.8K reputationPosted Dec 27, 2009, 6:20 PM EST
ItemList myItemList = new ItemList(2); you need to do this myItemList.items[0] = new item(); myItemList.items[1] = new item(); then you can do myItemList.items[0].someData = 100;Kirtan PatelRank #292 · 8.6K reputationPosted Dec 27, 2009, 9:29 PM EST
you have unselected my answer ...
Lali11 reputationPosted Dec 27, 2009, 9:34 PM EST
public ItemList(int count) { itemCount = count; items = new Item[count]; // Allocates array pointers for (int i = 0; i < count; i++) { items[i] = new Item(); // Allocate and assign Item instance } }Lali11 reputationPosted Dec 27, 2009, 9:40 PM EST