Link to home
Start Free TrialLog in
Avatar of cowiekspert
cowiekspert

asked on

Create array of "type" class

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

Avatar of divyeshhdoshi
divyeshhdoshi

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";

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



Avatar of cowiekspert

ASKER

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 ?
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
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);
}
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
ASKER CERTIFIED SOLUTION
Avatar of Priest04
Priest04
Flag of Serbia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
You can use loop to instantiate all the elements ,
There is no way to instantiate all array elements directly.

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