Having a type declaration with two sub-types deriving from the same internal type, how can we have a different record helper for each sub-type?
Example:
type
SingleA = Single;
SingleB = Single;
_SingleA = record helper for SingleA
procedure DoThingsToA;
end;
_SingleB = record helper for SingleB
procedure DoThingsToB;
end;
if I declare a var of type SingleA, i always get the helper from type SingleB, i know this to be normal behaviour if we override the same internal type, but why does it happen with different types?
Any help much appreciated...
Thanks in advance.
You are not declaring sub-types here. This code:
type
SingleA = Single;
SingleB = Single;
Is merely declaring aliases, not types. As such, SingleA
and SingleB
are actually the same type Single
.
This is explained here:
Type Compatibility and Identity (Delphi)
When one type identifier is declared using another type identifier, without qualification, they denote the same type. Thus, given the declarations:
type T1 = Integer; T2 = T1; T3 = Integer; T4 = T2;
T1
,T2
,T3
,T4
, andInteger
all denote the same type. To create distinct types, repeat the wordtype
in the declaration. For example:type TMyInteger = type Integer;
creates a new type called
TMyInteger
which is not identical toInteger
.
In effect, the = type x
construct creates new type info for the type so thatTypeInfo(SingleA) <> TypeInfo(SingleB)
.
In your original code, you are just declaring two aliases for the same type Single
.
For any given type (and its aliases), you can only have one type helper in scope, so in your original code the record helper for SingleB
hides the record helper for SingleA
.
By upgrading the aliases to their own types, you avoid this issue:
type
SingleA = type Single;
SingleB = type Single; <<-- the type keyword makes SingleB distinct from SingleA
Now you will have two distinct types, and your record helpers will work as expected.
Unfortunately, when you declare
type
SingleA = Single;
Delphi sees this as an alias rather than a derived type.
So it sees, in your case, SingleA, SingleB and Single as all being identical. (You can see this by declaring a function with parameter of type SingleA and attempting to pass a SingleB parameter to it).
So Following the rule that for any one type there can only be one helper, and helper for SingleB was the last defined then, as you comment, the behaviour is to be expected.
You can also see this by stepping through your code and looking at parameter type of a variable of type SingleA or SingleB in local variable window, foe instance. You will see that it is always specified as type Single.
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