Understanding and Using .NET Attributes

Introduction to Attributes

Attributes are a means of associating declarative
information with your code. They are metadata of sorts that you can use on
types, methods, and properties that are evaluated at runtime. The .NET
Framework
predefines and uses attributes to control runtime behavior.
Common uses of attributes include but are not limited to the following:

  • Controlling serialization behavior
  • Specifying code access security requirements
  • Marking obsolete code
  • Creating self-configuring objects

The following code snippet shows an object where attributes
are used to control the shape of the XML output:

using System;
using System.Xml.Serialization;
namespace TestSerialization
{
[XmlRoot("TestDataXml")]
public class TestData
{
[XmlElement("DataName")]
public string Name { get; set; }

[XmlIgnore]
public string IgnoreMe { get; set; }
}
}

The following code snippet demonstrates the use of
attributes for declarative security:

[FileIOPermission(System.Security.Permissions.SecurityAction.Demand, Read= @"C:helloworld.txt")]
public class Form1 : System.Windows.Forms.Form
{
//...
}

Creating Custom Attributes

Custom attributes are classes that are used to provide
additional descriptive information about properties, methods, etc. used in your
classes. The information from the attribute can be obtained programmatically
using our friend Reflection.

A custom attribute begins with the AttributeUsage
attribute, which defines the way your attribute class can be used. Since a
custom attribute uses an attribute it provides one example of how attributes
can be used just by creating a custom attribute. There are three parameters
that can be applied to your custom attributes. The AttributeTargets
defines where the attribute can be used, for example, properties, methods, classes,
etc. The Inherited parameter defines whether or not classes that are derived
from classes that use your attribute inherit your attribute as well. The AllowMultiple
parameter defines whether or not multiple instances of your parameter can exist
on an item.

Here is an example of a custom attribute created to map an
object property to a configuration file entry. The attribute consists of a
FieldName that contains the name of the configuration file element that stores
the setting.

///
/// Attribute used to indicate if a property should be configured
/// by the Configurator object. It is valid only on Properties and
/// only one attribute is allowed per property.
///
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ConfiguratorFieldAttribute : Attribute
{
/// Name of the data field
public string FieldName { get; set; }
///
/// Constructor
///
/// Name of the data field
public ConfiguratorFieldAttribute(string FieldName)
{
this._FieldName = FieldName;
}
}

Reading Attributes with Reflection

One of the common ways that attributes are used at runtime
is through reflection.
The following sample code will demonstrate using reflection to read all of the
attributes assigned to properties of an instance of an object. The attribute
that will be read is based on the ConfiguratorFieldAttribute we defined above.
The following code snippet defines our test object and shows the properties
decorated with our custom attribute:

public class TestObject
{
[ConfiguratorField("Parameter1")]
public string Property1 { get; set; }
[ConfiguratorField("Parameter2")]
public string Property2 { get; set; }
[ConfiguratorField("Parameter3")]
public string Property3 { get; set; }
}

The following code snippet demonstrates a method that would
take an instance of our TestObject or other object and traverse the properties
for those with our custom attribute. When found it will call the method to set
the properties value based on some answer retrieved from the GetSetting method.

public void ConfigureObject(object ObjectToConfig)
{
ConfiguratorFieldAttribute attr; // Custom ConfigurationFieldAttribute
object[] attributes; // Attributes assigned to the object
PropertyInfo property; // Object property
// List of object properties
PropertyInfo[] itemTypeProps = ObjectToConfig.GetType().GetProperties();
// Loop through all of the properties of the object
for( int i = 0; i < itemTypeProps.Length; i++ )
{
// Get the current ConfiguratorField attribute
property = itemTypeProps [i];
attributes = property.GetCustomAttributes(typeof(ConfiguratorFieldAttribute), true);
// Verify the ConfiguratorField attribute was found
if( attributes != null && attributes.Length == 1 )
{
// Set the value
attr = (ConfiguratorFieldAttribute) attributes[0];
if( property != null )
{
property.SetValue(ObjectToConfig, this.GetSetting(attr.FieldName), null);
}
}
}
}

About the Author:

Mark Strawmyer is a Senior Architect of .NET applications
for large and mid-size organizations. Mark is a technology leader with Crowe Horwath LLP in Indianapolis,
Indiana. He specializes in architecture, design and development of
Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for
application development with C# again. You can reach Mark through http://markstrawmyer.com.

More by Author

Must Read