[fpc-pascal] Case based on type

Sven Barth pascaldragon at googlemail.com
Fri Mar 1 23:57:18 CET 2013


On 01.03.2013 23:35, Mark Morgan Lloyd wrote:
> Given a procedure definition like
>
> procedure checkLibrariesAndConnect(db: TSQLConnection);
>
> is there a more elegant way of performing type-specific actions than
>
> begin
>    if db is TPQConnection then begin
>    end;
>    if db is TIBConnection then begin
>    end
> end { checkLibrariesAndConnect } ;
>
> i.e. something like  case TypeOf(db)  ?
>

No, there is currently no such construct. You could do this though:

=== example begin ===

procedure checkLibrariesAndConnect(db: TSQLConnection);

   procedure SetupPQConnection(db: TSQLConnection);
   // ...

   procedure SetupIBConnection(db: TSQLConnection);
   // ...

type
   TConnectionInitializer = record
     Connection: class of TSQLConnection;
     Setup: procedure(db: TSQLConnection) is nested; // needs 
{$modeswitch nestedprocvars}
   end;

const
   ConnectionTypes: array[0..1] of TConnectionInitializer = (
     (Connection: TPQConnection; Setup: @SetupPQConnection),
     (Connection: TIBConnection; Setup: @SetupIBConnection)
   );
var
   conn: TConnectionInitializer;
begin
   for conn in ConnectionTypes do
     if db is conn.Connection then begin
       conn.Setup(db);
       Break;
     end;
end;

=== example end ===

Alternatively if you don't need to check the hierarchy, but can live 
with an exact match you can do this:

=== example begin ===

procedure checkLibrariesAndConnect(db: TSQLConnection);
begin
   case LowerCase(db.ClassName) of
     // Note: .ClassName won't work here
     'TPQConnection': ...;
     'TIBConnection': ...;
   end;
end;

=== example end ===

Regards,
Sven



More information about the fpc-pascal mailing list