Attributes in C# provide a powerful method to add metadata to your code. They can be used to convey additional information to the runtime, compiler, or even to developers. While .NET provides several built-in attributes, there might be times when you need to define your own custom attributes to suit specific needs.

What Are Attributes?

Attributes are classes that inherit from the System.Attribute base class. They are used to decorate program elements such as classes, methods, properties, and fields with additional metadata. This metadata can then be accessed at runtime using reflection.

Creating a custom attribute involves the following steps:

  1. Define the Attribute Class: Create a class that inherits from System.Attribute.
  2. Add Constructors: Provide constructors to initialize the attribute.
  3. Apply the Attribute: Decorate your code elements with the custom attribute.

Let’s create a custom attribute named AuthorAttribute to store information about the author of a class.

using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false)]
public class AuthorAttribute : Attribute
{
    public string Name { get; }
    public string Version { get; }

    public AuthorAttribute(string name, string version)
    {
        Name = name;
        Version = version;
    }
}

In this example:

  • AttributeUsage specifies where this attribute can be applied (Class and Method in this case) and whether it can be inherited by derived classes.
  • The AuthorAttribute class has two read-only properties, Name and Version, which are initialized via the constructor.

Applying the Custom Attribute

Now that we have our custom attribute, let’s apply it to a class and a method:

[Author("Bob Marley", "4.2")]
public class SampleClass
{
    [Author("Dean Winchester", "19.67")]
    public void SampleMethod()
    {
        Console.WriteLine("This is a sample method.");
    }
}

Conclusion

Custom attributes in C# offer a flexible way to add metadata to your code, which can be useful for various purposes like documentation, code generation, and runtime behavior modification. By defining and using custom attributes, you can create more expressive and maintainable code.

In the future I might come back with more detailed examples for using this feature.

Affiliate promo

If you love learning new stuff and want to support me, consider buying a course from Dometrain using this link: Browse courses – Dometrain. Thank you!

Leave a comment

Trending