[fpc-pascal] Case based on type

Mark Morgan Lloyd markMLl.fpc-pascal at telemetry.co.uk
Sat Mar 2 00:10:24 CET 2013


Sven Barth wrote:
> 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;

Thanks Sven, noted with interest.  case LowerCase(...ClassName)  looks 
like "the best of a bad job", provided obviously that it's called 
infrequently.

-- 
Mark Morgan Lloyd
markMLl .AT. telemetry.co .DOT. uk

[Opinions above are the author's, not those of his employers or colleagues]



More information about the fpc-pascal mailing list