title: Is there any way to dynamically cast the item type of a generics collection in Delphi?
body: <p>Unlike the case with common objects, it is impossible to directly assign generics of different related types in Delphi as follows:</p>
  
  <p>Possible (normal objects):</p>
  
  <pre><code>var
     var_1 : TObject;
     var_2 : MyTObjectSubClass;
  
  var_1 := var_2; //Works
  </code></pre>
  
  <p>Not possible (generics):</p>
  
  <pre><code>var
     var_1 : TList&lt;TObject&gt;;
     var_2 : TList&lt;MyTObjectSubClass&gt;;
  
  var_1 := var_2; //Does not compile
  </code></pre>
  
  <p>It <em>is</em> possible to use casts to accomplish this though, as follows:</p>
  
  <pre><code>var
     var_1 : TList&lt;TObject&gt;;
     var_2 : TList&lt;MyTObjectSubClass&gt;;
  
  var_1 := TList&lt;TObject&gt;(var_2); //Works
  </code></pre>
  
  <p>This creates the need to be able to <em>dynamically</em> cast generics (i.e. to dynamically parameterize their generic type specification) somehow, but I have not been able to find a way to do this, so my question is: Is this in any way possible?</p>
  
  <p>I'm indeed aware of the <a href="https://stackoverflow.com/questions/22404734/wildcard-for-arbitrary-generic-list">covariance/contravariance problems</a> related to this, but in some cases it would indeed both be useful and "correct" to do such a thing.</p>
  
  <p>One example of such a situation is the current code I'm writing for generic streaming of Delphi objects over a <code>TStream</code>, where the receiving end knows the exact type of the object that is incoming over the stream, e.g. <code>TList&lt;MyTObjectSubClass&gt;</code>. This type information is extracted by means of RTTI though (from a provided target variable to which the loaded object should be written), so I <em>cannot</em> explicitly mention the exact generics type in my stream-loading code in advance, but rather have to detect it by means of RTTI (which is <a href="https://stackoverflow.com/questions/28922070/how-can-i-get-the-sub-item-type-of-a-tobjectlistt-purely-by-rtti-information">possible, although somewhat hacky</a>) and then write it to a target variable that I only at that run-time point will know the exact type of.</p>
  
  <p>Thus, the load-object-from-stream code has to be fully generic, and thus, it would need to dynamically cast an existing <code>TList&lt;TObject&gt;</code> variable (which <em>is</em> defined explicitly in the code) to the exact type of <code>TList&lt;MyTObjectSubClass&gt;</code> (which I at that point have just learned about, through the use of RTTI), in order to be able to pass this object loaded from the stream to its final destination variable.</p>
  
  <p>So again, is there ANY way whatsoever to accomplish this, or is it on the contrary actually completely impossible to assign to a not-in-advance-known generics collections using generic code (i.e. code that does not explicitly have some kind of "if [type of xxx is <code>TList&lt;TMyObject1&gt;</code>] then ... else if [type of xxx is <code>TList&lt;TMyObject2&gt;</code>] then ... else ..." test, containing explicit mentions of every single generics type that should be supported by it)?</p>
  
  <p>PS.
  The generics type of the stream-loaded object obviously already exists somewhere in the program (since it is concluded by means of RTTI on the target variable that the stream-loaded object should be written to), <strong>so I'm not asking about full run-time dynamic creation of generics types</strong>, but rather just about how to be able to dynamically <em>pick the right one of those generics types already defined at compile-time</em> in the program, and then cast a variable to that type.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>By request from @RemyLebeau , here comes some more example code from my application, from its stream-loading function:</p>
  
  <pre><code>var
     source_stream    : TStream;
     field_to_process : TRttiField;
     field_type       : TRttiType;
     loaded_value     : TValue;
     temp_int         : integer;
  
  //...
  //The fields of any object given to the streaming function are
  //enumerated and sorted here
  //...
  
  //Then, for each field (provided in field_to_process),
  //the following is done:
  
  case field_to_process.FieldType.TypeKind of
  
     //...
  
     tkInteger:
     begin
        source_stream.ReadBufferData(temp_int);
        loaded_value := TValue.From(temp_int);
     end;
  
     tkString,
     tkLString,
     tkWString,
     tkUString:
     begin
        source_stream.ReadBufferData(noof_raw_bytes_in_string_data);
        SetLength(raw_byte_buf, noof_raw_bytes_in_string_data + 4);
        source_stream.ReadBuffer(raw_byte_buf[0], noof_raw_bytes_in_string_data);
        temp_str := used_string_encoding.GetString(raw_byte_buf, 0, noof_raw_bytes_in_string_data);
        loaded_value := TValue.From(temp_str);
     end;
  
     tkClass:
     begin
        is_generics_collection_containing_TObject_descendants := &lt;does some hacky detection here&gt;; //Thanks Remy :-)
  
        if is_generics_collection_containing_TObject_descendants then
        begin
  
           &lt;magic code goes here that loads data from the stream into the currently processed field, whose type has been detected to be of some specific generics collection type&gt;
  
        end;
     end;
  
     //...
  
  end;
  
  field_to_process.SetValue(self, loaded_value);
  </code></pre>
  
  <p>That should hopefully give a somewhat better overview of my problem. The superfluous code for strings and integers are just for context, by showing how some simple types are handled.</p>
  
  <p>For more info about the (necessarily) "hacky detection" mentioned in the code, please see <a href="https://stackoverflow.com/questions/28922600/how-can-i-test-if-an-unknown-delphi-rtti-tvalue-reflects-an-object-that-is-any-t">this question</a>. After doing that, I will know the exact type of the generics collection and its subitems, for example <code>TList&lt;TSomeTObjectDescendant&gt;</code>.</p>
  
  <p>So, as you hopefully can see now, the question is about the <code>&lt;magic code goes here that loads data from the stream into the currently processed field, whose type has been detected to be of some specific generics collection type&gt;</code> part. How can it be implemented?</p>
  
  <p>NOTE: My problem is <strong>not</strong> to understand how to serialize/deserialize contents of an enumerable through a stream (which can of course be done by simply iterating over the items in the enumerable and then recursing the stream saving/loading code for each of them, where the number of items is given first of all in the stream). The problem is rather how to create generic code that will be able to recreate/populate any kind of generics collection of TObject descentants, whose type you only get to know at runtime, and then to finally get this into the object field that was originally enumerated by RTTI at the beginning of the stream-loading code. As an example, assume that the processed field has the type <code>TList&lt;TSomeTObjectDescendant&gt;</code>, and that you can easily load its subobjects from the stream using a call like <code>function load_list_TSomeTObjectDescendant_subitems(input_stream : TStream) : array of TSomeTObjectDescendant</code>. How could I then get these subitems into the <code>TList&lt;TSomeTObjectDescendant&gt;</code> field?</p>