473,692 Members | 2,028 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem instantiating an array of objects or array of class instances

Below is my problem. I've narrowed it down to one thing: my
unfamiliarity on how class instances are instantiated in an array.
This is because the "un-array" / "non-array" version of the program
works fine (see below). So what is the problem? I get a null
reference on the line below at *!&!* "Unhandled Exception:
System.NullRefe renceException: Object reference not set to
an instance of an object.?

RL
static void Main(string[] args)
{

int Array_Max1 = 5; // the size of the array

NodeTreeMgr[] myNodeTreeMgr = new NodeTreeMgr[Array_Max1];
//the array version of the class (compiles but gets runtime error)
// the problem is perhaps here--somehow the 'new' is not working in
this array

NodeTreeMgr mySingleNodeTre eMgr = new NodeTreeMgr();
// the non-array version of the class (works fine)

MyClass rootClass = new MyClass(123); //unimportant nested
class

Node[] myrootnode = new Node[Array_Max1];
// a class on the "LHS" of the "=" below

Node[] myBADrootnode = new Node[Array_Max1];
//same as previous line

for (int i = 0; i < 5; i++) //start of loop
{

myrootnode[i] =
mySingleNodeTre eMgr.TheNodeTre e.NodeFactory(r ootClass);
//works fine in runtime--since the RHS is a "non-array"

Console.WriteLi ne("success! myrootnode[{0}].child_TorF is {1}", i,
myrootnode[i].child_TorF); //works fine, returns a member bool
"false"

// start of problem code: *!&!* next line a problem, exception is
thrown

myBADrootnode[i] =
myNodeTreeMgr[i].TheNodeTree.No deFactory(rootC lass);

// if the above line is commented out, program works fine (loop runs
five times)

Console.WriteLi ne("NO success! WON'T WORK! (runtime
error): myBADrootnode[{0}].child_TorF is {1}", i,
myBADrootnode[i].child_TorF); //doesn't work

}

}

////////// output

success! myrootnode[0].child_TorF is False

Unhandled Exception: System.NullRefe renceException: Object reference
not set to
an instance of an object.

Press any key to continue . . .

/////////////////////// FYI OTHER CLASSES BELOW /////

class NodeTreeMgr
{
public NodeTree TheNodeTree;

public Node NodeFactory(MyC lass MyClaPass) //standard "Node
factory" class
{
Node returnNode = new Node();
returnNode.Val = MyClaPass;
return returnNode;
}
}

///////////////////////

class Node
{
public bool child_TorF;

public Node()
{
child_TorF = false;
}

}

private MyClass val; //val needed for below "Val"
public MyClass Val
{
get
{
return val;
}
set
{
val = value; //taking advantage of 'special variable
'value'
}
}

}

public class MyClass
{
public int j; public String STR1;
public MyClass() { STR1 = "hi"; j = 1; }
public MyClass(int jj) { j=jj;}
}

///////////////////////

Sep 13 '07 #1
3 6347
On Sep 13, 4:49 pm, raylopez99 <raylope...@yah oo.comwrote:
Below is my problem. I've narrowed it down to one thing: my
unfamiliarity on how class instances are instantiated in an array.
This is because the "un-array" / "non-array" version of the program
works fine (see below). So what is the problem? I get a null
reference on the line below at *!&!* "Unhandled Exception:
System.NullRefe renceException: Object reference not set to
an instance of an object.?

RL

static void Main(string[] args)
{

int Array_Max1 = 5; // the size of the array

NodeTreeMgr[] myNodeTreeMgr = new NodeTreeMgr[Array_Max1];
//the array version of the class (compiles but gets runtime error)
// the problem is perhaps here--somehow the 'new' is not working in
this array
The problem is that this creates an array of the given size, but
doesn't populate it - or rather, it fills it with null references.

If you want each element to be an instance of NodeTreeMgr, you need
something like:

for (int i=0; i < myNodeTreeMgr.L ength; i++)
{
myNodeTreeMgr[i] = new NodeTreeMgr();
}

Jon

Sep 13 '07 #2
On Sep 13, 8:55 am, "Jon Skeet [C# MVP]" <sk...@pobox.co mwrote:
NodeTreeMgr[] myNodeTreeMgr = new NodeTreeMgr[Array_Max1];
//the array version of the class (compiles but gets runtime error)
// the problem is perhaps here--somehow the 'new' is not working in
this array

The problem is that this creates an array of the given size, but
doesn't populate it - or rather, it fills it with null references.

If you want each element to be an instance of NodeTreeMgr, you need
something like:

for (int i=0; i < myNodeTreeMgr.L ength; i++)
{
myNodeTreeMgr[i] = new NodeTreeMgr();

}

Jon
Thanks Jon!

Dang, you're good! I see you all over the place, answering questions
from as far back as 2005. I would send you money if I could! (and if
you only had a nickel every time you've answered...)

THanks again,

RL

Sep 13 '07 #3
raylopez99 <ra********@yah oo.comwrote:
Dang, you're good! I see you all over the place, answering questions
from as far back as 2005. I would send you money if I could! (and if
you only had a nickel every time you've answered...)
Back earlier than that, in fact - although I'm sure others (eg Nick
Paldino) were involved in C# long before I was.

No need for money though - I've always benefitted *enormously* from the
newsgroup. I reckon the best way to learn things is to find out the
answers to questions other people ask :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Sep 17 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3328
by: James | last post by:
Hi, I'm hoping someone can help me out. If I declare a class, eg. class CSomeclass { public: var/func etc..... private varfunc etc..
1
7096
by: david | last post by:
I have a question (not sure if just a newbie one, or a stupid one) whose answer I couldn't find on the C# books and tutorials I could put my hands on. Consider the following useless class (could be a struct as well, if you just comment out the non static parameterless constructor) and the Main() routine : using System;
2
2190
by: david | last post by:
Well, as a matter of fact I_HAD_MISSED a basic thing or two, anyway, although Ollie's answer makes perfectly sense when dealing with classes, it doesn't seem to me to apply as well if you have to instantiate an array of structures; consider the following useless code : using System; struct MyPointS
3
1360
by: Nathan Sokalski | last post by:
I have an array declared as follows: Dim ButtonList() As NavButtonInfo and a Class defined as follows: Public Class NavButtonInfo Public Shared name As String
6
1619
by: Gary Frank | last post by:
What are the ramifications if I were to instantiate an object tens of thousands of times and add them to an array? Or hundreds of thousands of times? Do you know if the act of instantiating a class takes a lot of storage or other resources? Would it be a severe performance penalty? From the .Net help doc:
5
4573
by: Anders Borum | last post by:
Hello! Whilst refactoring an application, I was looking at optimizing a ModelFactory with generics. Unfortunately, the business objects created by the ModelFactory doesn't provide public constructors (because we do not allow developers to instantiate them directly). Because our business objects are instantiated very frequently, the idea of using reflection sounds like a performance killer (I haven't done any tests on this, but the...
19
2513
by: Chocawok | last post by:
Some of the classes in my app are graphical. To encapsulate the graphical side of things I had created a class called "sprite" which holds a bit map and knows how to draw itself etc. The classes that are graphical contain a sprite object.
7
6433
by: heddy | last post by:
I have an array of objects. When I use Array.Resize<T>(ref Object,int Newsize); and the newsize is smaller then what the array was previously, are the resources allocated to the objects that are now thown out of the array released properly by the CLI?
17
7245
by: =?Utf-8?B?U2hhcm9u?= | last post by:
Hi Gurus, I need to transfer a jagged array of byte by reference to unmanaged function, The unmanaged code should changed the values of the array, and when the unmanaged function returns I need to show the array data to the end user. Can I do that? How?
0
8600
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9079
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8954
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7626
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6458
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4322
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4555
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2234
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1955
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.