Kromster
Kromster

Reputation: 7436

How to declare custom types in Delphi?

I want to declare a custom data type for better code readability. The intent is to keep this type clean from any interference with other AnsiStrings. But Delphi seems to not support it?

type
  TKMLocaleCode = type AnsiString;

... snip ...

procedure A;
var 
  A,B: TKMLocaleCode;
  C: AnsiString; 
begin
  A := 'eng'; //<<-- I expect an error here
  A := C; //<<-- I expect an error here too

  B := TKMLocaleCode('eng'); //<<-- I expect no error here
end;

Is it possible to declare such a custom type in Delphi?

Upvotes: 2

Views: 2412

Answers (2)

David Heffernan
David Heffernan

Reputation: 613562

You can declare a record and then use operator overloading to supply whichever operators you wish to support:

type
  TKMLocaleCode = record
  strict private
    FValue: AnsiString;
  public
    class operator Explicit(const Value: string): TKMLocaleCode;
  end;

class operator TKMLocaleCode.Explicit(const Value: AnsiString): TKMLocaleCode;
begin
  Result.FValue := Value;
end;

Clearly you'll want to add more functionality, but this record meets the requirements stated in the question.

Upvotes: 5

Rob Kennedy
Rob Kennedy

Reputation: 163357

You shouldn't have gotten an error where you did, but your initial technique wouldn't accomplish your goal anyway. Notice how TFileName is a distinct string type just like yours, but it can be used anywhere an ordinary string is expected. The type declaration is more for establishing different RTTI for a type so that it can be used for different kinds of property editors at design time.

To really make a distinct type, try declaring a record with a field to hold your data. Records are not compatible with anything else, even when they have the same structure as another type. To make your record comparable with other values of the same type, overload the comparison operator by providing Equal and NotEqual methods in the record declaration. To allow creation of the distinct type through type casting, but not through ordinary assignment, provide an Explicit operator, but not Implicit.

Upvotes: 8

Related Questions