0

Delphi2010 compiles my TObjectListEnumerator class without error, but DelphiXE3 gives compiler error: E2089: Invalid typecast

What is wrong with this?

    TObjectListEnumerator<T> = class
      private
        fList     : TObjectList;
        fIndex    : integer;
        fMaxIndex : integer;
        function GetCurrent : T;
      public
        constructor Create(List: TObjectList);
        function MoveNext : Boolean;
        property Current  : T read GetCurrent;
      end;

    constructor TObjectListEnumerator<T>.Create(List: TObjectList);
    begin
      inherited Create;
      fList     := List;
      fIndex    := -1;
      fMaxIndex := fList.Count-1;
    end;

    function TObjectListEnumerator<T>.MoveNext: Boolean;
    begin
      Inc(fIndex);
      Result := not(fIndex > fMaxIndex);
    end;

    function TObjectListEnumerator<T>.GetCurrent: T;
    begin
      Result := T(fList[fIndex]);  // <-- E2089: Invalid typecast 
    end;
Sir Rufo
  • 18,395
  • 2
  • 39
  • 73
pKarelian
  • 263
  • 1
  • 8
  • 14
  • 4
    Not really an answer to your question, but since you are using generics, why don't you switch from the non-parameterized `TObjectList` to `TObjectList` from `System.Generics.Collections`? I guess that it would automatically help you so you wouldn't need the typecast there. – Pateman Jun 26 '13 at 20:19
  • Thanks Pateman, nice hint! If I use TObjectList, I don't need TObjectListEnumerator at all. – pKarelian Jun 27 '13 at 05:57

1 Answers1

2

As the documentation states: the property Items of Contnrs.TObjectList has the type TObject:

property Items[Index: Integer]: TObject read GetItem write SetItem; default;

On the other hand, the type parameter T is unconstrained and can be any type, for example a value type like Integer.

If you add a generic type constraint, the code should compile:

TObjectListEnumerator<T: TObject> = class
ventiseis
  • 3,029
  • 11
  • 32
  • 49
  • If first thought about `TObjectListEnumerator = class` but documentation is [saying](http://docwiki.embarcadero.com/RADStudio/XE3/en/Constraints_in_Generics#Class_Constraint): "This means that the actual type must be a reference type, that is, a class or _interface_ type". – ventiseis Feb 05 '16 at 20:46