Home  |  Delphi .net Home  |  System.Collections.HashTable  |  CopyTo Method
Copies elements from the HashTable to a single dimension array
HashTable Class
System.Collections NameSpace
CF1.  Procedure CopyTo ( TargetArray : System.Array; TargetIndex : Integer ) ;
CF : Methods with this mark are Compact Framework Compatible
The CopyTo method takes all elements from the current HashTable and overlays these values onto elements of the TargetArray.
The overlay starts at the TargetIndex value.
Important : the TargetArray must be created in advance - the CopyTo method overlays - it does not build. Also, the target array must have at least the same capacity as the number of elements being overlaid (copied).
Important : the TargetArray data type must be able to accomodate the DictionaryEntry type in the copy process. If the CopyTo method cannot cast to the target array, then an exception is thrown.
Just like Clone, CopyTo performs a shallow copy. When the current HashList holds reference (non primitive) data types, the target array element values still refer to the same objects that current array elements refer to. This is what is referred to as a shallow copy. A deep copy would create new versions of the referred objects.
Microsoft MSDN Links
 Author links

 Buy Website Traffic at

 Buy Proxies at
Copying the whole HashTable onto the middle of an Array
program Project1;


  MyTable   : System.Collections.HashTable;
  MyArray   : System.Array;
  DictEntry : DictionaryEntry;
  i         : Integer;

  // Create our hash table
  MyTable := HashTable.Create;

  // And fill it
  MyTable['Age']      := TObject(47);
  MyTable['Birthday'] := DateTime.Create(1957, 2, 18);
  MyTable['Name']     := 'Neil Moffatt';

  // Create the target array
  MyArray := System.Array.CreateInstance(TypeOf(TObject), 9);

  // And fill it
  MyArray.SetValue('0.', 0);
  MyArray.SetValue('1.', 1);
  MyArray.SetValue('2.', 2);
  MyArray.SetValue('3.', 3);
  MyArray.SetValue('4.', 4);
  MyArray.SetValue('5.', 5);
  MyArray.SetValue('6.', 6);
  MyArray.SetValue('7.', 7);
  MyArray.SetValue('8.', 8);

  // Copy to the array
  Console.WriteLine('Copying from HashTable to the array :');
  MyTable.CopyTo(MyArray, 3);

  // Display the array contents
  for i := 0 to MyArray.Length-1 do
    if MyArray.GetValue(i).GetType = TypeOf(String)
    then Console.WriteLine('String : {0}',

    if MyArray.GetValue(i).GetType = TypeOf(DictionaryEntry)
      DictEntry := DictionaryEntry(MyArray.GetValue(i));
      Console.WriteLine('Dictionary entry : {0} = {1}',

   Copying from HashTable to the array :
   String : 0.
   String : 1.
   String : 2.
   Dictionary entry : Birthday = 18/02/1957 00:00:00
   Dictionary entry : Age = 47
   Dictionary entry : Name = Neil Moffatt
   String : 6.
   String : 7.
   String : 8.
Delphi Programming Neil Moffatt All rights reserved.  |  Contact the author