delphivariablesdeclarationpascal

Can I declare variables in-line instead of at the top of a function?


I have used visual basic about 5 years ago.

but i have started using delphi 5 years ago (when most developers jumped from delphi to visual studio) delphi is as easy as vb and at the same time it is rad and robust. Delphi is having many changes since pascal (eg : strings must be combined in a different way in pascal instead of just using + ) in order to make scripting faster.

but why in delphi we have to declare var on top , when i am writing many statements for a procedure i have to scroll up and declare a var and come down again. delphi is one of the best(some times one and only) MOST RAPID'est' IDE in the world but why they did not give support to declare variable anywhere just as in vb c# etc


Solution

  • From Delphi version 10.3 Rio it is possible to declare variables and constants inline.

    Even the type can be inferred.

    Examples:

    procedure Test1;
    begin
      var i : Integer;
      i := 10;
      WriteLn(i);
    end;
    

    Variables can be inlined and assigned:

    procedure Test2;
    begin
      var i : Integer := 10;
      WriteLn(i);
    end;
    

    Inlined variable types can be inferred:

    procedure Test3;
    begin
      var i := 10;
      WriteLn(i);
    end;
    

    Scope of inlined variables can be limited to begin/end blocks:

    procedure Test4;
    begin
      var i : Integer := 10;
      WriteLn(i);
      if i < 20 then begin
         var j := 30;
      end;
      Write(j); // <- Compiler error “Undeclared identifier: ‘j’”
    end;
    

    Inlined variables can be used inside for-in or for-to loops:

    procedure Test5;
    begin
      for var i := 1 to 10 do
        WriteLn(i);
    end;
    

    Constants can also be inlined and type can be inferred as normal constants:

    procedure Test6;
    begin
      const i : Integer = 10;
      const j = 20;
      WriteLn(j);
    end;