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
public class TestData
public string Name { get; set; }

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
public string Property1 { get; set; }
public string Property2 { get; set; }
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.

About the Author

Mark Strawmyer

Mark Strawmyer is a Senior Architect of .NET applications for large and mid-size organizations. 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# for the fifth year in a row. You can reach Mark at mark.strawmyer@crowehorwath.com.

Related Articles


  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Moving from an on-premises environment to Office 365 does not remove the need to plan for disruptions or reduce the business risk requirements for protecting email services. If anything, some risks increase with a move to the cloud. Read how to ease the transition every business faces if considering or already migrating to cloud email. This white paper discusses: Setting expectations when migrating to Office 365 Understanding the implications of relying solely on Exchange Online security Necessary archiving …

  • Enterprises are increasingly looking to platform as a service (PaaS) to lower their costs and speed their time to market for new applications. Developing, deploying, and managing applications in the cloud eliminates the time and expense of managing a physical infrastructure to support them. PaaS offerings must deliver additional long-term benefits, such as a lower total cost of ownership (TCO), rapid scalability, and ease of integration, all while providing robust security and availability. This report …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date