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
  • 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 ?
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.


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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
C# Json POSt to Rest API 4 60
Server Error 11 58
C# 2015 Downloading text file and preserving the line breaks 5 36
Cant save 3D 4 19
Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

813 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now