equin0x80
equin0x80

Reputation: 313

What does "property" mean on this attribute?

[property: Obsolete]
static int X
{
    get { return 42; }
}

In the code above, what purpose does the word "property" serve? The code seems to work the same way if I replace [property: Obsolete] with [Obsolete]. And although "property" is coloured blue in Visual Studio, it does not appear in the list of C# keywords: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/

Upvotes: 1

Views: 253

Answers (2)

Patrick Hofman
Patrick Hofman

Reputation: 156928

This is an attribute target specification.

In your code the use of it is not really necessary, since there is just one allowed target for that attribute at that place. The Obsolete attribute can be placed on a type, method or a property, but if placed on a property, only the property target specifier is allowed (and used implicitly).

The most practical use for this is the assembly target specifier, where you can set assembly configuration through attributes:

[assembly: AssemblyProduct("Foo bar")]

You can set the allowed targets on your custom attributes using AttributeUsage.

Upvotes: 1

hardkoded
hardkoded

Reputation: 21597

The Attribute specification defines this as an attribute target.

Certain contexts permit the specification of an attribute on more than one target. A program can explicitly specify the target by including an attribute_target_specifier. When an attribute is placed at the global level, a global_attribute_target_specifier is required. In all other locations, a reasonable default is applied, but an attribute_target_specifier can be used to affirm or override the default in certain ambiguous cases (or to just affirm the default in non-ambiguous cases).

It also states that in many cases, like the one you mention, it is permitted but not necessary.

In other contexts, inclusion of an attribute_target_specifier is permitted but unnecessary. For instance, a class declaration may either include or omit the specifier type.

Upvotes: 1

Related Questions