Attributes in C# allow us to assign meta data to code (classes or methods etc.).
There are many scenarious for their usage, for example the Serializable attribute is used to mark the class as one that can be serialized.
[Serializable]
public class Person
{
}
Now, we'll learn how to create a custom attribute. We create a class that extends Attribute base class and has AttributeUsage attribute assigned to it. It indicates that this attribute is intended for usage with classes and structs. Then, we create a simple constructor with one string attribute and a method used to access this value.[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class AuthorAttribute : Attribute
{
private readonly string _name;
public AuthorAttribute(string name)
{
_name = name;
}
public string GetName()
{
return _name;
}
}
We can assign our custom attribute to a class, passing in a string "Matt" as a parameter.[Author("Matt")]
public class Person
{
}
In the Main method we can access our attribute using reflection. We use the GetCustomAttributes method to reach all attributes assigned to the class Person. Then, we can search for the attribute of type AuthorAttribute. We can use Console.Writeline() and GetName() methods to display the value of the attribute in the console window.class Program
{
static void Main(string[] args)
{
var attributes = Attribute.GetCustomAttributes(typeof(Person)); // Reflection
var authorAttribute = attributes.OfType<AuthorAttribute>().Single();
Console.WriteLine(authorAttribute.GetName());
Console.ReadLine();
}
}