Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use String instead of TFilename?

When passing filename parameters to procedures/functions, should I use TFilename or String.

If there is a difference, what is it, and what are then potential ramifications if using a String?

e.g.

procedure TForm1.OpenFile(const AFilename : String);
begin
    //Open the file if it exists
    ...
end;
like image 733
Simon Avatar asked May 02 '12 14:05

Simon


People also ask

Which method is used to create strings for filenames?

String[] list(): This method generates a list of strings of all the filenames present in the directory. File[] listFiles() :This method puts together an array and returns it. The array contains all the pathnames of the files present in the directory.

What is the difference between a path and a file name?

A file name is a name a particular inode is called inside a particular directory. A path is some instructions for how to reach an inode from a known point.


3 Answers

I think TFilename should be used when developing components because that way IDE can show it's property editor (TOpenDialog will be shown when clicked on ellipsis in the property inspector).

Other than this there is basically no difference which one to use. Remember that if you use TFilename you must add SysUtils to your uses clause.

like image 113
Linas Avatar answered Oct 17 '22 22:10

Linas


The only practical difference between string and TFileName types in a plain code is in passing an argument by reference; the following code

procedure GetFileName(var FileName: TFileName);
begin
  FileName:= 'abcd.abc';
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  S: string;

begin
  GetFileName(S);
end;

does not compile with error

[DCC Error] E2033 Types of actual and formal var parameters must be identical
like image 42
kludg Avatar answered Oct 17 '22 23:10

kludg


Maybe this is a bit too obvious, but using the string type doesn't communicate anything about the intended usage of a variable. But when you encounter a variable declared as a TFileName, there's a lot more detail communicated right there.

The same principle applys to other basic types like Integer, Cardinal, Double etc. Instead you might want to consider using aliases for these like TCustomerID, THashValue, TInterestRate, etc. as these communicate much clearer what the intended usage of these variables is.

This improves readablility, and also allows for changing the base-type when needed, without having to touch any code using the type... just a recompile and you're done (but do be carefull with binary compatibility ofcourse).

like image 44
PatrickvL Avatar answered Oct 17 '22 21:10

PatrickvL