It’s been a wish for a very very long time: to get the name of an identifier as a string in Delphi:
- [WayBack] How to get current method’s name in Delphi 7? – Stack Overflow
- [WayBack] How To Get the Name of the Current Procedure/Function in Delphi (As a String) – Stack Overflow
For now the best one can do is either using an Assert and catching the exception (it gets you the unit name, source file name and source line number) in the links below, or using debug symbol information (like a MAP or TDS file) mentioned in the StackOverflow questions above.
C# has had a [WayBack] nameof
for many years now that is evaluated at compile time: [WayBack] c# – Is nameof() evaluated at compile-time? – Stack Overflow.
There is a request RAD Studio – RSP-13290: NameOf(T) compiler (magic) function in Quality Portal by Horácio Filho about 3 years ago quotes below.
Since it took the C# team about 3 years after the original [WayBack] Add nameof operator in C# – Visual Studio request, I wonder how fast the Delphi team is.
NameOf .NET-like compiler magic (intrinsic) function would eliminate a lot of hand-written exception messages from several units.
C# 6 introduced nameof operator to obtain the simple (unqualified) string name of a variable, type, or member.
With the current Delphi implementation, after changing variables name we have ot change the related exception message as well. Putting variables name in the code is not a good practise, and is here that NameOf taking place saving tons of lines of code. As the result of NameOf(T) function (if so) is evaluated at compile time (according to the C# implementation – http://stackoverflow.com/a/26573179) we need a help from compiler or it could be achieved using RTTI.
There is a discussion on Google+ community [WayBack] https://plus.google.com/+StefanGlienke/posts/AsGHSLF4rTX.
The function could be designed as
NameOf(x: Identifier)
following the same (or similar) warranties C# provides.
Using Assert:
- Delphi – class helper to get SourceFileName from an EAssertionFailed « The Wiert Corner – irregular stream of stuff
- Delphi – getting the sourcefile name from a source file with an Assert trick using EAssertionFailed « The Wiert Corner – irregular stream of stuff
–jeroen