csharp-atributos

Attributes in C#

  • 4 min

Attributes in C# are special classes used to add metadata to code elements.

This metadata can be read and used by the compiler, development tools, or the program itself at runtime through reflection.

Attributes derive from the base class System.Attribute.

This metadata provides additional information about program elements, such as classes, methods, properties, among others.

Attribute Syntax

An attribute is declared by placing the attribute name within square brackets ([ ]) just before the declaration of the element it applies to. For example:

[Serializable]
public class Example { }

[Obsolete("This method is obsolete")]
public void OldMethod() { }
Copied!

In these examples, Serializable and Obsolete are attributes that provide additional information about the Example class and the OldMethod method, respectively.

Using Predefined Attributes

There are many predefined attributes in .NET. Let’s look at some of them.

Defining and Using Custom Attributes

In addition to using predefined attributes, it is also possible to define custom attributes according to the developer’s specific needs.

To define a custom attribute, you create a class that derives from System.Attribute and add any necessary properties or fields.

Defining a Custom Attribute

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorAttribute : Attribute
{
    public string Name { get; }
    public string Date { get; }

    public AuthorAttribute(string name, string date)
    {
        Name = name;
        Date = date;
    }
}
Copied!

In this example, a custom attribute AuthorAttribute is defined with two properties: Name and Date.

Using a Custom Attribute

[Author("Luis", "01/06/2023")]
public class Example
{
    [Author("Luis", "01/06/2023")]
    public void ExampleMethod()
    {
        // Method code
    }
}
Copied!

Here, the Author attribute is applied to both the Example class and the ExampleMethod method, providing information about the author and date.

Reading Attributes at Runtime

Reflection in C# allows reading attributes applied to code elements at runtime. This is done using classes from the System.Reflection namespace.

Type type = typeof(Example);

foreach (var attribute in type.GetCustomAttributes(typeof(AuthorAttribute), false))
{
	AuthorAttribute author = (AuthorAttribute)attribute;
	Console.WriteLine($"Class - Author: {author.Name}, Date: {author.Date}");
}

MethodInfo method = type.GetMethod("ExampleMethod");
foreach (var attribute in method.GetCustomAttributes(typeof(AuthorAttribute), false))
{
	AuthorAttribute author = (AuthorAttribute)attribute;
	Console.WriteLine($"Method - Author: {author.Name}, Date: {author.Date}");
}
Copied!

In this example, the Author attributes applied to the Example class and the ExampleMethod method are read and displayed.