NullReference Exception on new'ed array(?)

  • Thread starter Thread starter SteveK
  • Start date Start date
S

SteveK

given this code:
TreeNode[] n = new TreeNode[10];

n[0].Text = "test";


does it make sense that I should get a NULL Reference Exception when
assigning to .Text?
Isn't that the whole point of 'new TreeNode[10]'

Any help appreciated, thanks!
 
No, that creates a new array object that can hold TreeNodes. Each 'slot' in
the array however, is initially null, however. You have to initialize each
slot to a TreeNode object.
 
Try:

TreeNode[] n = new TreeNode[10];
n[0].Text = new TreeNode("test");

Hope it helps
Boaz Ben-Porat
 
OK, I understand, thank you both for your help, everything is working fine
now :)


Marina said:
No, that creates a new array object that can hold TreeNodes. Each 'slot' in
the array however, is initially null, however. You have to initialize each
slot to a TreeNode object.

SteveK said:
given this code:
TreeNode[] n = new TreeNode[10];

n[0].Text = "test";


does it make sense that I should get a NULL Reference Exception when
assigning to .Text?
Isn't that the whole point of 'new TreeNode[10]'

Any help appreciated, thanks!
 
Back
Top