views:

192

answers:

1

I am trying to implement clear in the following example code in Delphi 2009.

interface
...
  TFoo<T : IInterface> = class(TObject)
    FField : T;
    procedure Clear;
  end;
...
implementation
...
procedure TFoo<T>.Clear;
begin
  // Line Below Results In
  //  E2010 Incompatible types: 'T' and 'Pointer' 
  FField := nil;
end;
...

I could understand the complie time error if "T" was not constrained. But since "T" must be an Interface, I would have thought this syntax would have worked.

Is there away to set FField to NIL, so the interface can be released?

+13  A: 

Instead of nil you must use the new Default(T) which returns the default value for the generic parameter type. And for interfaces it is nil

procedure TFoo<T>.Clear;
begin
  FField := Default(T);
end;
Andreas Hausladen
There are a lot of problems with Generics in D2009. Most of them are supposed to be solved in the next update, whenever it comes out. Looks like this is one of them. Try reporting it to QC, and until then, this solution is probably your best workaround.
Mason Wheeler
Pleasantly surprised to see that the reference counting code was emitted as well.
Ryan VanIderstine