Have an amazing solution built in RAD Studio? Let us know. Looking for discounts? Visit our Special Offers page!

New Tip: TBooleanHelper.ToString and TUseBoolStrs enumeration

the future of starts demands massive productivity

Among the native type record helpers that were introduced in the Delphi RTL a few years back, there is one for the Boolean data type. It has a few methods you can apply to a Boolean variable, including ToString. This is the class helper definition:

If you call ToString on a Boolean variable you get 0 or -1 depending on the value. In other words, True.ToString produces -1.

The ToString method has also a second parameter, UseBoolStrs, to let the method return a string with the text False or True.  However, if you call True.ToString(True) you still get -1. What’s up? As you can see in the definition above, there are both a regular instance method and a class method called ToString that can be called with one Boolean parameter. The compiler picks the one without default parameter as best match. 

So the question is, how can I get the desired string output? Simply by using the TUseBoolStrs enumeration. In fact, originally the signature of the methods was using a Boolean as parameter, that is the values False or True. More recently, this was changed to use a TUseBoolStrs enumerator, with identical values False or True. In this way, the existing code compiles. The advantage of this trick you can specify the full value of the parameter, using the type as prefix and write:

This returns the string True, which is what we wanted in the first place. It it not an obvious solution, but it allows keeping the existing code compatible while addressing a design limitation (the two methods with the same name) that was already there. The only problem is that few Delphi developers realize this — I was ignoring the solution until recently — and this is why I just wrote this blog post!

Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.
Start Free Trial   Upgrade Today

   Free Delphi Community Edition   Free C++Builder Community Edition

About author

Marco is one of the RAD Studio Product Managers, focused on Delphi. He's the best selling author of over 20 books on Delphi.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.