views:

398

answers:

1

Hi there.

I'm learning Delphi Prism, and i don't find how to write the following code with it :

type
  TRapportItem = record
   Label : String;
   Value : Int16;
   AnomalieComment : String;
  end;

type 
  TRapportCategorie = record
    Label : String;
    CategoriesItems : Array of TRapportItem;
  end;

type 
  TRapportContent = record
    Categories : array of TRapportCategorie;
  end;

Then, somewhere, i try to put items in the array :

rapport.Categories[i].Label:=l.Item(i).InnerText;

But it doesn't work.. Can someone enlight me?

Thanks!

+5  A: 
  • You didn't specify exactly what "didn't work". You should include the error in questions like this.
  • Arrays are reference types, and they start out with the value nil. They need to be initialized before elements can be accessed.

You can do this with the new operator:

rapport.Categories = new TRapportCategorie[10]; // 0..9
  • Arrays are quite a low-level type. Usually it's better to work with List<T> instead.

So you'd declare:

Categories: List<TRapportCategorie>;
  • But lists also need initializing, using the new operator. Also, modifying the return value of the indexer on a list containing a value type will be modifying a copy, not the original, which leads to the next point.
  • Records are usually not the best data type for representing data, as they are not reference types; it's very easy to end up modifying a copy of the data, rather than the original data. It's usually best to use classes instead, where you can put all the initialization code (such as allocating the array or list) in the constructor.
Barry Kelly
Thank you! I switched to the use of a list and it now works!rapport.Categories:= new List<TRapportCategorie>;Using some kind of classe was planned, because this code will have to be used by two different apps, but i wanted some kind of quick prototyping here.Thanks!
Pierre
+1 on using a List<T> or Dictionary<T> with the key as the category name instead.
jamiei