Question

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!

Was it helpful?

Solution

  • 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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top