#468 – Attributes Allow Adding Metadata to Program Elements
December 5, 2011 4 Comments
You can use an attribute to specify metadata that you want attached to some element in your application. There are a number of predefined attributes in the .NET Framework, for various purposes. You can also define your own custom attributes.
You can find a list of all predefined attributes here.
Here are a few examples of predefined attributes that you might use:
- DebuggerDisplay – Tells Visual Studio how to display summary information about a type in a window that shows the current value of an object
- Obsolete – Indicates that a method is obsolete and should no longer be used (issues a warning at compile time)
- Serializable – Indicates that a type can be serialized (stored as a sequence of bytes).
- WebMethod – Indicates that a method can be used through an XML web service
Pingback: #469 – Attaching an Attribute to a Type Member « 2,000 Things You Should Know About C#
Typo: “an attribute specify” → ‘an attribute to specify’
There are tons of built-in attributes:
https://docs.microsoft.com/en-us/dotnet/api/system.attribute?redirectedfrom=MSDN&view=net-5.0#inheritanceContinued
The more broadly applicable ones (in my experience, and in addition to those listed above) include Flags, ThreadStatic, Conditional, DebuggerStepThrough, InternalsVisibleTo, and Browsable.
Oh, another newer feature: [field: SomeAttribute] on an auto-property allows you to apply SomeAttribute to the auto-generated backing field. This was mistakenly placed at the bottom of the Local Functions section of this page: https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#local-functions