Monday, October 22, 2012

Multiple Attributes on One Line

Apparently Delphi (at least XE2, didn’t test with others) allows you to write a comma-separated attribute list inside square brackets when annotating types and type members.

IOW, following two code fragments are identical.

[Name(CNameModule2Sub1)]
[Description('Submodule 2.1)]
TModule2Sub1Info = class
end;
[Name(CNameModule2Sub1), Description('Submodule 2.1')]
TModule2Sub1Info = class
end;

I am not able to find if this is a documented behavior.

Disclaimer: Yes, I know that stringing attributes one after another can make your code less readable. It can, however, also make it more readable if you have multiple attributes applied to fields in a class.

TExample = class
  [Attr1]
  [Attr2]
  [Attr3('something something')]
  Field1: string;
  [Attr1]
  [Attr2]
  [Attr3('halleluyah')]
  Field2: integer;
end;
TExample = class
  [Attr1, Attr2, Attr3('something something')]
  Field1: string;
  [Attr1, Attr2, Attr3('halleluyah')]
  Field2: integer;
end;

1 comment: