Reading Attribute Data

Learn to create custom attributes.

Introduction

Attributes are special constructs that let us inject additional metadata into an assembly. Attributes can be applied both to the entire type (class, struct, interface) and to individual parts of the type (properties, methods, fields). Attributes have many applications. Most often, we use them to validate that a member or type meets certain conditions.

Suppose we have a minimum length requirement for a password in our system. We have a class called UserProfile with the following definition:

public class UserProfile
{
	public string Username { get; set; }
	public string Password { get; set; }
}

To achieve our objective, we could simply create a method that checks if the Password property is greater than or equal to the minimum length. But, what if we later want to enforce the minimum length rule on the Username property as well? We’d have to change the method for minimum length validation so that it also checks the Username property. For each property we want to enforce the minimum length rule, we have to add a corresponding check.

What if it was possible to simply modify the property with an attribute that tells the program to validate compliance to the minimum length rule? Fortunately, it’s possible with the help of reflection and attributes.

Create attributes

An attribute in .NET is represented by the System.Attribute class. Whenever we want to create a custom attribute, we create a new class and derive it from System.Attribute**:

public class MinLengthAttribute : Attribute
{
}

Although we may name our attributes whatever we want, it’s conventional to have the Attribute ending.

To check the minimum length, we must have a place where we declare this minimum value:

public class MinLengthAttribute : Attribute
{
	public int MinLength { get; set; }
	
	public MinLengthAttribute() { }
	public MinLengthAttribute(int minLength)
	{
		MinLength = minLength;
	}
}

We create one property to hold the minimum length, and two constructors: one empty and one that sets the value of the MinLength property.

After creating our custom attribute, we can modify the properties that we want to enforce our minimum length rule on:

public class UserProfile
{
	// Username must be at least 10 characters long
	[MinLength(10)]
	public string Username { get; set; }

	// Password must be at least 15 characters long
	[MinLength(15)]
	public string Password { get; set; }
}

When modifying a type or member with an attribute, the Attribute suffix can be dropped. For instance, in the code snippet above, our properties are modified with the MinLength attribute. We could have put the full name (MinLengthAttribute), but that’s not necessary.

As a last step, we must create a method that checks if properties modified with the MinLength attribute conform to the requirements:

Get hands-on with 1200+ tech skills courses.