class as an array?  
Author Message
pessi





PostPosted: Visual C# Language, class as an array? Top

dear all

I am a beginner in c# and would like your help. I will describe my problem in a simple fashion below.

I have 3 building (say numbered 0, 1 and 2) with books in them. So I create a class called Books.

I have created a class called Books
in Books I have properties like PaperQuality, Quantity etc.

now in my main program I want something like,

Books[] bk = new Books[20];

and have something like

bk[0].PaperQuality = "nice";
bk[0].quantity = 20;

etc...

it doesnt work. gives an exception.

System.NullReferenceException was unhandled
Message="Object reference not set to an instance of an object."

it says on this line.
bk[0].PaperQuality = "nice";

use the new keyword to create an instance of an object.

can someone suggest where I am going wrong

cheers,
prasad..













Visual C#15  
 
 
PhilipRieck





PostPosted: Visual C# Language, class as an array? Top

You have created space for 20 "Books" objects with the line:

Books[] bk = new Books[20];

but you didn't create any actual "Books" instances in the array. Think of "bk[0]" as just another variable name - you need to assign something to it before using it.

//Create a new array that can hold 20 Books
Books[] bk = new Books[20];
for(int i = 0; i< 20; i++)
{
  //Now, create each book in the array
  bk[ i ] = new Books();
}

bk[0].PaperQuality = "nice";
...

 

 


 
 
pessi





PostPosted: Visual C# Language, class as an array? Top

Thanks a ton! that worked.


 
 
ashk1860





PostPosted: Visual C# Language, class as an array? Top

hi dear pessi

when you use expression:

Books[] bk = new Books[20];

you are just assigning the array objects and then you can have access to your array. but the objects of your array are not construct yet. so if you want to assign values to the attributes of your objects inside your array you have to construct them also. like this:

for (int i = 0; i < 20 ;++i )

bkIdea = new Books();

then you can have access to each of the objects inside your array

regards


 
 
pessi





PostPosted: Visual C# Language, class as an array? Top

that is what I did. I saw a null reference error and saw that I had to initialise them.

BTW if possible please help with the XML question I have in another thread.
Thank you again.

 
 
ashk1860





PostPosted: Visual C# Language, class as an array? Top

oops