Question

In my studying process I use "Coding in Delphi" book by Nick Hodges. I am using Delphi 2010.

In the chapter about anonymous methods, he provides a very interesting example about faking .NET using. When I try to compile the example, I get an error from the compiler. Please help me to get a result.

My class:

type
  TgrsObj = class
    class procedure Using<T: class>(O: T; Proc: TProc<T>); static;
  end;

implementation

{ TgrsObj }

class procedure TgrsObj.Using<T>(O: T; Proc: TProc<T>);
begin
  try
    Proc(O);
  finally
    O.Free;
  end;
end;

Here is how I try to use the code above:

procedure TForm4.Button1Click(Sender: TObject);
begin
  TgrsObj.Using(TStringStream.Create,
    procedure(ss: TStringStream)
    begin
      ss.WriteString('test string');
      Memo1.Lines.Text := ss.DataString;
    end);
end;

Compiler error:

[DCC Error] uMain.pas(36): E2010 Incompatible types: 'TProc<ugrsObj.Using<T>.T>' and 'Procedure'
Was it helpful?

Solution

That is because type inference in Delphi is poor. It could in fact infere T from the first parameter but unfortunately the compiler is not satisfied then for the second parameter which would perfectly match.

You have to explicitly state the type parameter like this:

TgrsObj.Using<TStringStream>(TStringStream.Create, procedure(ss: TStringStream)
  begin
    ss.WriteString('test string');
    Memo1.Lines.Text := ss.DataString;
  end);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top