Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hi,

Thanks for your time. I have a naive C# question about dynamic creation of objects.

 

MyClass a = new MyClass(); works

 

but

 

MyClass [] a = new MyClass[2]; does not...It does not give any errors but the value is null and when I try to invoke a method on the class it gives an exception {"Object reference not set to an instance of an object."}

 

Am I missing something simple?

 

Thanks again.

G

Posted

Objects and arrays

 

The second statement is allocating an array of length 2 for storing MyClass objects. The objects themselves must be instantiated individually:

 

MyClass[] a = new MyClass[2];

MyClass[0] = new MyClass();
MyClass[1] = new MyClass();

 

Good luck :cool:

Never trouble another for what you can do for yourself.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...