Take the 2-minute tour ×

The following example is giving me this error:
[DCC Error] Unit2.pas(54): E2010 Incompatible types: 'IBar' and 'Unit2.TFoo<Unit2.IBar>'

I think the problem is somewhere around the Self.Create Because after many tries to get it compiled I accidentally entered FFoo := TBar(Self).Create; and it compiled and worked.

I'm using Delphi XE

IFoo = interface

TFoo<T: IInterface> = class(TInterfacedObject, IFoo)
private class var
  FFoo: T;
public class
  function Instance: T;

IBar = interface(IFoo)

TBar = class(TFoo<IBar>, IBar)

class function TFoo<T>.Instance: T;
  if not Assigned(FFoo) then
    FFoo := Self.Create;
  Result := FFoo;
share|improve this question
The error tells you a line number. Perhaps you could point out exactly what line that is instead of guessing where the problem might be? –  Anon. Jan 23 '11 at 22:15
The error is on the line after "end." –  RjK Jan 23 '11 at 22:59
The cast TBar(Self).Create is unwanted as you are not sure that Self is a TBar and it will break the concept of generics (not usable for another class)! –  TridenT Jan 24 '11 at 8:53
It is really a shame what line numbering is not supported here. –  Free Consulting Jan 24 '11 at 10:06
add comment

2 Answers

The problem is in this line with the TBar declaration:

FFoo := Self.Create;

To understand, let's explain the types behind the code [noted like this]:

FFoo:[IBar] := Self:[TFoo(IBar)].Create():[TFoo<IBar>]

So, tu summarize, we have : [IBar] := [TFoo<IBar>]
Are these types compatible ?
A [TFoo] only implements IFoo interface, no IBar as it is stated in your code


This is the compilation error !
UPDATE : Solution 1
To fix the issue : change the TBar declaration

TBar = class(TFoo<IFoo>, IBar)

UPDATE : Solution 2
Replace the FFoo := Self.Create by

FFoo := Self.Create.Instance;

and so it works !

share|improve this answer
That's not the solution because the result type of the function Instance will be IFoo and not IBar. –  RjK Jan 24 '11 at 16:01
@RjK: I've updated my post with Solution 2. I think this is what were searching ! –  TridenT Jan 24 '11 at 19:35
UPDATE : Solution 2 -> This will cause a stack overflow. –  RjK Jan 24 '11 at 20:59
add comment

Your TFoo does not implement T as interface. That's why FFoo and an instance of TFoo is not compatible. If you want to assign an instance of TFoo to FFoo you need to hardcast it.

share|improve this answer
Do you mean this in the function Instance : Result := T(FFoo); It compiles but when I run it I get an AV on the last end of the function. (Access violation at address 00000001. Read of address 00000001.) –  RjK Jan 24 '11 at 17:55
add comment

Your Answer


