...

/

Reading Attribute Data

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 ...