CodeBlanks Logo Icon CodeBlanks

Custom attributes

C# course · Advanced · Lesson 50/83

Learn to write your own attribute class with AttributeUsage.

Writing a custom attribute

To write a custom attribute, you define a class that derives from Attribute. For convenience the name should end with ...Attribute. Example: public class NoteAttribute : Attribute { }.

You can add properties and a constructor to carry data. With [AttributeUsage] you specify where it can apply (class, method, property) and whether multiple uses are allowed.

AttributeUsage

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] specifies where an attribute can apply and whether multiple uses are allowed. The AttributeTargets enumeration lists the target kinds.

Common targets: Class, Method, Property, Field, Assembly. AllowMultiple = true allows applying the attribute more than once to the same element. Inherited = true lets it propagate to derived classes.

Exercise Define NoteAttribute and apply it

Define the NoteAttribute class in the skeleton below: mark it with [AttributeUsage(AttributeTargets.Class)], derive from Attribute, add a Text property and a constructor taking string text. Apply [Note("Important")] to the Sample class. In Main, read the attributes with typeof(Sample).GetCustomAttributes(true) and print each one's type name with Console.WriteLine.

Show example solution
[AttributeUsage(AttributeTargets.Class)] public class NoteAttribute : Attribute { public string Text { get; set; } public NoteAttribute(string text) { Text = text; } }. Add [Note("Important")] to Sample. In Main read with typeof(Sample).GetCustomAttributes(true) and print with foreach (var a in attrs) { Console.WriteLine(a.GetType().Name); }.
Example solution:
using System;

[AttributeUsage(AttributeTargets.Class)]
public class NoteAttribute : Attribute
{
    public string Text { get; set; }
    public NoteAttribute(string text) { Text = text; }
}

[Note("Important")]
class Sample { }

class Program
{
    static void Main()
    {
        var attrs = typeof(Sample).GetCustomAttributes(true);
        foreach (var a in attrs)
        {
            Console.WriteLine(a.GetType().Name);
        }
    }
}

Test yourself

  1. Complete the attribute class declaration

    public class MyAttribute : ____ { }
    Show answer
    public class MyAttribute : Attribute { }
  2. Which class does a custom attribute derive from?

    • MemberInfo
    • Attribute
    • Type
    • Object
    Show answer

    Attribute — Correct. A custom attribute derives from Attribute.

  3. Match the element to its meaning

    AttributeUsage
    Specifies target
    AttributeTargets
    Target kinds
    AllowMultiple
    Multiple usage
    Inherited
    Applies to derived classes

All lessons in Advanced