Solved

Create array of "type" class

Posted on 2008-10-17
10
1,283 Views
Last Modified: 2012-06-27
Hi
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

0
Comment
Question by:cowiekspert
  • 3
  • 3
  • 2
  • +2
10 Comments
 
LVL 6

Expert Comment

by:divyeshhdoshi
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";

0
 
LVL 7

Expert Comment

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



0
 

Author Comment

by:cowiekspert
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 ?
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 7

Expert Comment

by:lucky_james
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.

James
0
 
LVL 13

Expert Comment

by:crazyman
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);
}
0
 

Author Comment

by:cowiekspert
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 ?

Sveinung
0
 
LVL 18

Accepted Solution

by:
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

Goran.
0
 
LVL 7

Expert Comment

by:lucky_james
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).

James
0
 
LVL 6

Expert Comment

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

0
 

Author Comment

by:cowiekspert
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 !
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

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 This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

829 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