Click here to Skip to main content
15,906,947 members
Please Sign up or sign in to vote.
4.40/5 (2 votes)
See more:
Hi,

I'm trying to Instantiate a new object and store the object into an array. I am receiving "Object reference not set to an instance of an object." I can't figure out what I've done wrong, it looks right to me. Any help is greatly appreciated.

MyExcel[] myexcel = null;
int excel = 0;
...
foreach (KeyValuePair<string, string> kvp in Common.divisionDictionary)
{
    myexcel[excel] = new MyExcel();         // Instantiate an instance of Excel

    path = Common.SpreadsheetDirectory;
    ...
}

I'm receiving the error on:
myexcel[excel] = new MyExcel();


However if I assign it like this it works perfect:
MyExcel Excel = new MyExcel();


Thank you,
Glenn
Posted
Comments
Dr.Walt Fair, PE 10-Dec-10 19:02pm    
The error is exactly what it says it is. You need to initialize the array before you assign anything to its members, since the members don't exist yet.

MyExcel[] myexcel = null;

...

myexcel[excel] = new MyExcel();         // Instantiate an instance of Excel

You cannot store an item into an array that does not exist. You need to allocate some entries to myexcel - at least as many as will be encountered in your foreach loop.
 
Share this answer
 
You didn't allocate memory for the array.

For instance, changing from
MyExcel[] myexcel = null;

to (say)
MyExcel[] myexcel = new MyExcel[10];


would fix your program.
:)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900