static problem? Object reference not set to an instance of an object

M

Michael Meckelein

ASP.NET 1.1, c# web application

I get an exception "Object reference not set to an instance of an object"
for the follwoing line:
myProductItem[0].ProductName = strProductName;

I have a class for product information "productitem":

public class productitem
{
public string ProductName;
public double ProductPrice;
public int ProductQuantity;
public int ProductDiscount;

public productitem()
{
//
// TODO: Add constructor logic here
//
this.ProductName = "";
this.ProductPrice = 0;
this.ProductQuantity = 0;
this.ProductDiscount = 0;
}

// I have declare an array of the productitem class as static:
public static productitem[] myProductItem;

// In my program I do the follwing
if (myProductItem == null)
{
myProductItem = new productitem[1000];
}

myProductItem[0].ProductName = strProductName; // here the exception occur
....

What's my fault?

Thanks in advance,
Michael
 
M

Martin Dechev

Hi, Michael,

This:
myProductItem = new productitem[1000];

is equal to:

myProductItem = new productitem[1000]
{null,null,null,...};

not to

myProductItem = new productitem[1000]
{new productitem(), new productitem(), ...};

That's why an exception is thrown:
myProductItem[0].ProductName = strProductName; // here the exception occur

at this point myProductItem[0] is null reference.

Hope this helps
Martin
 
M

Michael Meckelein

Martin Dechev said:
This:
myProductItem = new productitem[1000];

is equal to:

myProductItem = new productitem[1000]
{null,null,null,...};

not to

myProductItem = new productitem[1000]
{new productitem(), new productitem(), ...};

That's why an exception is thrown:
myProductItem[0].ProductName = strProductName; // here the exception
occur

at this point myProductItem[0] is null reference.

That's right. Thank you Marin for your great assistance!

Michael
 
K

Kevin Spencer

You created an array, but an array is just an array of nulls until you
populate it, just as an array of strings has no strings in it until you
assign a string to each element. In other words, taking the analogy of a
variable as a box, you created 1000 empty boxes.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top