Can I use reserved words for field names?

For compatibility reasons (objects are serialized and exported and must match external names) I would like the field name to be "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 it even possible? How?

+7
delphi
source share
3 answers

Try using and before the field name

+6
source share

Yes, you must use before the name;

 TTBaseWebResponse = class private &type: String; success: Integer; end; 
+5
source share

This is described in the documentation :

Extended identifiers

You may encounter identifiers (for example, types or methods in the class) with the same name as the reserved word in Delphi. For example, a class may have a method called begin . Delphi reserved words are such since begin cannot be used for the identifier name.

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

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

As a shorter alternative, you can use the ampersand operator ( & ) to eliminate ambiguities between identifiers and the Delphi language reserved words. & prevents the parsing of the keyword as a keyword (i.e., a reserved word). If you come across a method or type this is the same name as the Delphi keyword, you can omit the namespace if you prefix the identifier name with an ampersand. But when you declare an identifier that has the same name as the keyword, you should use & :

 type &Type = Integer; // Prefix with '&' is ok. 
+5
source share

All Articles