C# Attributes


Occasionally, either because the framework you are using demands it or because you choose to, you will make use of attributes in your code. You can add attributes to classes, methods and other members using [AttributeName] syntax, and you can create your own attributes by deriving from System.Attribute. You can read attribute values through reflection.

As an example, it is possible to add an attribute to a method that tells Visual Studio not to step into the code when you debug it. You will need to add a using statement to employ this attribute: using System.Diagnostics.

[DebuggerStepThrough]
public void BoringMethod() { ... }

The attribute in the above code is [DebuggerStepThrough]. All attributes are added in this way. Enclose the name of the attribute in square brackets just before the target to which they apply. You can add multiple attributes to a single target either by separating them with commas or by enclosing each one in square brackets. The attribute above is implemented in a class called DebuggerStepThroughAttribute. In this example, the compiler creates an instance of the attribute class and associates it with the class method.

Some attributes are customizable through constructor parameters or properties and these can be specified when you add the attribute. In the example below the attribute is passing a value of 1000 to the constructor of DoesInterestingThingsAttribute and setting the value of a property called WhatDoesItDo to the string “yipee”.

[DoesInterestingThings(1000, WhatDoesItDo = "yipee")]
public class DecoratedClass {}

Another attribute that is used in these posts is Serializable.

Reading Attributes

In order to read attribute values you have to use a technique called reflection. This is a somewhat advanced technique that allows you to dynamically inspect information at runtime, even to the point where you can create object and call methods without knowing what those objects are. Reflection will not be discussed here.

Leave a comment

Your email address will not be published. Required fields are marked *