Jan Doggen
Jan Doggen

Reputation: 9096

Is it possible to use reserved words for field names?

For compatibility reasons (objects are serialized and exported and must match external names) I would like to have a field name being 'type', i.e.

TTBaseWebResponse = class
private
   type: String;
   success: Integer;       
end;

or

TTBaseWebResponse = class
private
   ftype: String;
   fsuccess: Integer;       
public
   type: string read fstring write fstring;
   success: integer read fsuccess write fsuccess;   
end;

Delphi (XE2) won't even compile this. Is this at all possible? How?

Upvotes: 9

Views: 3041

Answers (3)

David Heffernan
David Heffernan

Reputation: 612993

This is covered by the documentation:

Extended Identifiers

You might encounter identifiers (e.g. types, or methods in a class) having the same name as a Delphi language reserved word. For example, a class might have a method called begin. Delphi reserved words such as begin cannot be used for an identifier name.

If you fully qualify the identifier, then there is no problem. For example, if you want to use the Delphi reserved word type for an identifer name, you must use its fully qualified name:

var TMyType.type
// Using a fully qualified name avoids ambiguity with Delphi language keyword.

As a shorter alternative, the ampersand (&) operator can be used to resolve ambiguities between identifiers and Delphi language reserved words. The & prevents a keyword from being parsed as a keyword (that is, a reserved word). If you encounter a method or type that is the same name as a Delphi keyword, you can omit the namespace specification if you prefix the identifier name with an ampersand. But when you are declaring an identifier that has the same name as a keyword, you must use the &:

type
  &Type = Integer; 
  // Prefix with '&' is ok.

Upvotes: 8

Darthman
Darthman

Reputation: 457

Yes, you must use & before name;

TTBaseWebResponse = class
private
  &type: String;
  success: Integer;       
end;

Upvotes: 6

Kenny Cason
Kenny Cason

Reputation: 12328

Try using & before the field name

Upvotes: 12

Related Questions