Home > Enterprise >  Is there a StringHelper for TCaptions?
Is there a StringHelper for TCaptions?

Time:02-24

Is there a unit I can add to provide a StringHelper for TCaption?

Using Edit1.Text.Trim, Edit1.Text.ToInteger, etc is much neater than Trim(Edit1.Text), StrToInt(Edit1.Text), etc.

CodePudding user response:

Unfortunately not.

TCaption is defined as

type
  TCaption = type string;

which makes it a different type from string (because of the second type) so TStringHelper will not be used for TCaption. And there is no TCaptionHelper = record helper for TCaption (which would ideally be identical to TStringHelper).

This is very annoying in this case, but this behaviour of the language is what makes it possible for me to define my own TShoeSize = type Integer and add my own TShoeSizeHelper = record helper for TShoeSize without losing the Integer helper.

I have personally suggested in the Embarcadero Jira a feature that would let you copy or inherit a record helper; in this case, you could use such a feature to tell Delphi that TCaption should have the same helper as string.

But until the language is changed -- or someone just copy-pastes TStringHelper into a TCaptionHelper -- the best you can do is this:

ShowMessage(string(Edit1.Text).ToUpper)

But beware that this is dangerous!

What if you accidentally write

ShowMessage(string(Edit1).ToUpper)

That will compile (a pointer is a pointer...).

CodePudding user response:

There is no class helper for TCaption, no.

TCaption is a distinct type from string with its own RTTI for DFM purposes, so the standard TStringHelper will not recognize it as a string.

I would expect a type alias like TCaption to have access to its base type's helpers, but alas, that is not the case. There are already reports for this issue in QualityPortal: RSP-13736, RSP-16486, RSP-36474, etc.

In the meantime, the best you can do is just cast the TCaption to a string, eg:

string(Edit1.Text).Trim
string(Edit1.Text).ToInteger
...

Otherwise, you would have to write your own class helper for TCaption that delegates its work to the standard string helper.

  • Related