Solved

Create array of "type" class

Posted on 2008-10-17
10
1,273 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
Comment Utility
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
Comment Utility
as divyeshhdoshi as already pointed out, the problem is in instantiation of each individual object.



0
 

Author Comment

by:cowiekspert
Comment Utility
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
 
LVL 7

Expert Comment

by:lucky_james
Comment Utility
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
Comment Utility
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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:cowiekspert
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
You can use loop to instantiate all the elements ,
There is no way to instantiate all array elements directly.

0
 

Author Comment

by:cowiekspert
Comment Utility
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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
C# remove trailing commas from csv file 10 44
How do I get the id from URL? 19 46
Expando 4 33
COnsume rest client 6 4
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This video discusses moving either the default database or any database to a new volume.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

762 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

9 Experts available now in Live!

Get 1:1 Help Now