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;
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.
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.
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.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With