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; } }
}
|
Kirtan PatelPosted Dec 27, 2009, 11:02 PM
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();
}
}
LaliPosted Dec 28, 2009, 2:40 AM
LaliPosted Dec 28, 2009, 2:34 AM
Kirtan PatelPosted Dec 28, 2009, 2:29 AM
you have unselected my answer ...
theLizardPosted Dec 27, 2009, 11:20 PM
LaliPosted Dec 27, 2009, 7:33 PM
Kirtan PatelPosted Dec 27, 2009, 2:58 AM