Home  |  Delphi .net Home  |  System.Collections.SortedList  |  CopyTo Method
Copies elements from the SortedList to a single dimension array
SortedList 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 SortedList 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 SortedList 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 SortedList onto the middle of an Array
program Project1;


  MyList    : System.Collections.SortedList;
  MyArray   : System.Array;
  DictEntry : DictionaryEntry;
  i         : Integer;

  // Create our sorted list
  MyList := SortedList.Create;

  // And fill it
  MyList['Age']      := TObject(47);
  MyList['Birthday'] := DateTime.Create(1957, 2, 18);
  MyList['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 SortedList to the array :');
  MyList.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 SortedList to the array :
   String : 0.
   String : 1.
   String : 2.
   Dictionary entry : Age = 47
   Dictionary entry : Birthday = 18/02/1957 00:00:00
   Dictionary entry : Name = Neil Moffatt
   String : 6.
   String : 7.
   String : 8.
Delphi Programming Neil Moffatt 2002 - 2017. All rights reserved.  |  Contact the author