Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / September 2007

Tip: Looking for answers? Try searching our database.

Problem instantiating an array of objects or array of class instances

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
raylopez99 - 13 Sep 2007 16:49 GMT
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.NullReferenceException: 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 mySingleNodeTreeMgr = 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] =
mySingleNodeTreeMgr.TheNodeTree.NodeFactory(rootClass);
//works fine in runtime--since the RHS is a "non-array"

Console.WriteLine("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.NodeFactory(rootClass);

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

                Console.WriteLine("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.NullReferenceException: 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(MyClass 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;}
   }

///////////////////////
Jon Skeet [C# MVP] - 13 Sep 2007 16:55 GMT
> Below is my problem.  I've narrowed it down to one thing:  my
> unfamiliarity on how class instances are instantiated in an array.
[quoted text clipped - 15 lines]
> // 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.Length; i++)
{
   myNodeTreeMgr[i] = new NodeTreeMgr();
}

Jon
raylopez99 - 13 Sep 2007 19:05 GMT
> >             NodeTreeMgr[] myNodeTreeMgr = new NodeTreeMgr[Array_Max1];
> >  //the array version of the class (compiles but gets runtime error)
[quoted text clipped - 14 lines]
>
> 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
Jon Skeet [C# MVP] - 17 Sep 2007 19:16 GMT
> 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 :)

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.