Create array of "type" class

Posted on 2008-10-17
Last Modified: 2012-06-27
I am new to C# (used to Fortran and Pascl etc.)  What I wold like to do in C# is to make an array of class instances.  When I run the attached code I receive an error that sais "use the new keyword to create an object instance"  This happends in the line ResultatTabell[0].ord = "Hallo";

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Collections
	public class Tabell
	    public string ord;
	    public int antall;
	    public string forekomst;
	    public int strofeFlest;
	 class Program
		static void Main(string[] args)
		    SamleTabell[] ResultatTabell;
		    ResultatTabell = new SamleTabell[100];
		    ResultatTabell[0].ord = "Hallo";

Open in new window

Question by:cowiekspert
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +2

Expert Comment

ID: 22738817
You have created array in right way.

You need to instantiate each element of an object with new keyword.

like ResultatTabell[0]=new ResultatTabell();
ResultatTabell[0].ord = "Hallo";


Expert Comment

ID: 22738854
as divyeshhdoshi as already pointed out, the problem is in instantiation of each individual object.


Author Comment

ID: 22739022
Thanks for your help so far, but I need several hundred instances of this object, so maybe I am going about this the wrong way.  Any suggestion ?
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Expert Comment

ID: 22739028
do you mean instances of the array? for that you can code a loop to instantiate them.

or you mean that same instance to be used in two different flows? this has to be taken care by design.

Let me know, if you have any issue.

Hope this helps.

LVL 13

Expert Comment

ID: 22739147
This would instansiate all you elements, but how do you see getting the .ord property set in each ?

SamleTabell[] ResultatTabell = new SamleTabell[100];
for (int x =0; x<  ResultatTabell.Length;x++)
ResultatTabell[x] = new SamleTabell();
ResultatTabell[x].ord = String.Format("This is item {0}",x);

Author Comment

ID: 22739148
Thank you - this work:

for (int i = 0; i < words.Length; i++) ResultatTabell[i] = new SamleTabell();
New question :o)   Can this be done as a part of a constructor ?

LVL 18

Accepted Solution

Priest04 earned 125 total points
ID: 22739212
cowiekspert, I see you are confused about how array works. You said it yourself

>> but I need several hundred instances of this object

note the key word instance. I will give two examples that will help you understand it

MyClass[] arr = new MyClass[100]; // MyClass is a reference type
int[] arr2 = new int[100]; // int is a value type

Not lets look at arr, its an array that will contain 100 instances of MyClass. Since MyClass is a reference type, it has created 100 REFERENCES to a MyClass - it didnt create any object of MyClass type. So

arr[0] // this one contains a null value (reference = null), since no object is created. When the object is created, it will contain a ference to this created object. This is very similar to next scenario

ArrayList arr = new ArrayList(); // we created a collection that will hold our objects

MyClass obj = null; // this one created a reference to my obj, obj is not instantiated, its value is null

arr.Add(obj); // we added a reference which has a null value (no object associated with it), the same as we did when we created arr Array.

All this above is applied to reference types. What about value types?

int[] arr2 = new int [100];

Value types hold the value itself, not the reference to a object on the heap. So, when instantiating 100 elements of the int array, since int is a value type, every element will contain the VALUE itself.

arr[0] = 5; // is possible, since value types contain the value itself, no heap is involved, and no references are needed therefore.

So, to summarize:

Type                                      STACK                                                            HEAP
value type                             value                                                            
reference type                       reference to object on the heap                   object

MyClass[3] arr = new MyClass[3];

STACK                    HEAP
pointer1 = null       no object associated
pointer2 = null       no object associated
pointer3 = null       no object associated

MyClass[1] = new MyClass(); // now we instantiate object (on the heap), got its memory location (reference) ,and assigned it to the 2nd element of the array

STACK                              HEAP
pointer1 = null                 no object created
pointer2 = pointer           object
pointer3 = null                 no object created


Expert Comment

ID: 22739249
wonderful explanation Goran.......appreciate it!

Sveinung: hope that the doubt would have got cleared. Do let us know if you face any issue(s).


Expert Comment

ID: 22739683
You can use loop to instantiate all the elements ,
There is no way to instantiate all array elements directly.


Author Comment

ID: 22739724
As lucy james says: wonderful explanation Goran.......appreciate it!   This made everything much clearer. And now my code works -  Hurray !  Thank you all !

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question