Search code examples
delphidelphi-2006

Delphi 2006 - routine parameter untyped


It is possible to have a parameter in a routine which can be in the same time either an type, either an string? I know I can accomplish this by overloading a routine, I ask if it possible to do it in another way.

Assume that I have this type - TTest = (t1,t2,t3). I want to have a routine which accepts a parameter of type TTest, but in the same time to be a String, so I can call it myproc(t1) or myproc('blabla')


Solution

  • Even this can be easily accomplished with overloaded functions, considering it's a good exercise, based on David Hefferman's and Sertac Akyuz answers I made a small example to test both solutions. It is not perfect, it only shows both possibilities.

    unit Unit4;
    
    interface
    
    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs;
    
    type
      ttest = (t1,t2);
      TForm4 = class(TForm)
        procedure FormCreate(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
        function my(aVar:Variant):String;
        function MyUntype(const aVar):String;
      end;
    
    var
      Form4: TForm4;
    
    implementation
    
    {$R *.dfm}
    
    { TForm4 }
    
    procedure TForm4.FormCreate(Sender: TObject);
    var aTestTypeVar : ttest;
        aString : String;
    begin
     my(t1);
     my(t2);
     my('ssss');
    //with untyped params
     aString := 'aaaa';
     MyUntype(aString);
     aTestTypeVar := t1;
     aString := IntToStr(Ord(aTestTypeVar));
     MyUntype(aString);//can not be a numeral due to delphi Help
    end;
    
    function TForm4.my(aVar: Variant): String;
    begin
     showmessage(VarToStr(aVar));//shows either the string, either position in type
    end;
    
    function TForm4.MyUntype(const aVar): String;
    begin
     //need to cast the parameter  
     try
      ShowMessage(pchar(aVar))
     except
      showmessage(IntToStr(Ord(ttest(aVar))));
     end;
    end;
    
    end.
    

    Also I know that Variants are slow and must be used only needed.