title: Delphi Generic List to string
body: <p>I am looking at a generic list which can be written to an Array of string for any object based on a particular field. The base List will have a number of descendants. The Code for the declaration is shown below and compiles fine:</p>
  
  <pre><code>unit TestList;
  
  interface
  
  uses
    System.Classes, System.Rtti, System.Generics.Collections, system.SysUtils;
  
  type
    TMakeString&lt;T&gt; = reference to function(const input: T): String;
  
    TMyList&lt;T&gt;=class(TList&lt;T&gt;)
    protected
      function GenericAsString(const Value): string;
      Function CastToString(const Value: T): string; virtual;
    public
      Function MakeArray:TArray&lt;string&gt;;
    end;
  
    TMyObject=class(TObject)
    private
      fname: string;
    public
      property Name:string read fname write FName;
    end;
  
    TMyObjectList&lt;T:TMyObject&gt;=class(TMyList&lt;T&gt;)
    protected
      Function CastToString(const Value: T): string; override;
    end;
  
  implementation
  
  { TMyList&lt;T&gt; }
  
  function TMyList&lt;T&gt;.CastToString(const Value: T): string;
  begin
    result:='';
    if TypeInfo(T) = TypeInfo(string) then
      Result := GenericAsString(Value);
  end;
  
  function TMyList&lt;T&gt;.GenericAsString(const Value): string;
  begin
    Result := String(Value);
  end;
  
  function TMyList&lt;T&gt;.MakeArray: TArray&lt;string&gt;;
  var
    i:integer;
  begin
    setlength(Result,0);
    for i := 0 to count-1 do
      Result[i]:=CastToString(Items[i]);
  end;
  
  { TMyObjectList&lt;T&gt; }
  
  function TMyObjectList&lt;T&gt;.CastToString(const Value: T): string;
  begin
    result:=TMyObject(T).Name;
  end;
  
  end.
  </code></pre>
  
  <p>When I implement this code using the following:</p>
  
  <pre><code>var
    MyList:TMyList&lt;string&gt;;
    AList1:Tarray&lt;string&gt;;
  
  begin
    MyList:=TMyList&lt;string&gt;.create;
    MyList.Add('Name1');
    MyList.Add('Name1');
    Alist1:=MyList.MakeArray;
  end;
  </code></pre>
  
  <p>I keep getting an AV during the MakeArray call when it calls the CastToString function and tries to return a result. The same happens when I invoke the TMYObjectList at the same point.</p>
  
  <p>I am not sure if my use of generics here is effective or appropriate to this situation, and if not is there a better way to do this? I was toying with using an anonymous method approach as well but wasn't sure how to go about this.</p>