I know that attributes are extremely useful. There are some predefined ones such as [Browsable(false)]
which allows you to hide properties in the properties tab. Here is a good question explaining attributes: What are attributes in .NET?
What are the predefined attributes (and their namespace) you actually use in your projects?
Only a few attributes get compiler support, but one very interesting use of attributes is in AOP: PostSharp uses your bespoke attributes to inject IL into methods, allowing all manner of abilities... log/trace being trivial examples - but some other good examples are things like automatic INotifyPropertyChanged implementation (here).
Some that occur and impact the compiler or runtime directly:
[Conditional("FOO")]
- calls to this method (including argument evaluation) only occur if the "FOO" symbol is defined during build[MethodImpl(...)]
- used to indicate a few thing like synchronization, inlining[PrincipalPermission(...)]
- used to inject security checks into the code automatically[TypeForwardedTo(...)]
- used to move types between assemblies without rebuilding the callersFor things that are checked manually via reflection - I'm a big fan of the System.ComponentModel
attributes; things like [TypeDescriptionProvider(...)]
, [TypeConverter(...)]
, and [Editor(...)]
which can completely change the behavior of types in data-binding scenarios (i.e. dynamic properties etc).
[DebuggerDisplay]
can be really helpful to quickly see customized output of a Type when you mouse over the instance of the Type during debugging. example:
[DebuggerDisplay("FirstName={FirstName}, LastName={LastName}")]
class Customer
{
public string FirstName;
public string LastName;
}
This is how it should look in the debugger:
Also, it is worth mentioning that [WebMethod]
attribute with CacheDuration
property set can avoid unnecessary execution of the web service method.