C#
Reading attributes
Learn to read attributes with reflection.
Reading attributes
Attributes are read with reflection. Attribute.GetCustomAttribute(member, typeof(MyAttr)) returns a single attribute; GetCustomAttributes returns an array. The return value is object and must be cast to the real type.
This shows that an attribute is not only declared but also accessible at runtime. Providers, serializers and inspection tools use this to implement custom behavior.
Derived classes
GetCustomAttributes(true) returns inherited attributes too; false returns only those applied directly. The Inherited property on AttributeUsage controls whether the attribute propagates to derived classes.
For example, if a base class has [Note("Base")] and Inherited = true, the attribute can be read from the derived class too. With Inherited = false, it appears only on the class where it was directly applied.
Exercise Read NoteAttribute and print Text
Apply [Note("Hi")] to the Sample class below. In Main, read the attribute with Attribute.GetCustomAttribute(typeof(Sample), typeof(NoteAttribute)) as NoteAttribute and print the text with Console.WriteLine(attr.Text).
Show example solution
var attr = Attribute.GetCustomAttribute(typeof(Sample), typeof(NoteAttribute)) as NoteAttribute; Console.WriteLine(attr.Text);
Example solution:
using System;
[AttributeUsage(AttributeTargets.All)]
public class NoteAttribute : Attribute
{
public string Text { get; set; }
public NoteAttribute(string text) { Text = text; }
}
[Note("Hi")]
class Sample { }
class Program
{
static void Main()
{
var attr = Attribute.GetCustomAttribute(typeof(Sample), typeof(NoteAttribute)) as NoteAttribute;
Console.WriteLine(attr.Text);
}
}
Test yourself
-
Match the method to its return
- GetCustomAttribute
- Single attribute
- GetCustomAttributes
- Attribute array
- IsDefined
- Is it present?
- AttributeUsage
- Target restriction
-
Complete the GetCustomAttribute call
var attr = Attribute.____(typeof(Sample), typeof(NoteAttribute));
Show answer
var attr = Attribute.GetCustomAttribute(typeof(Sample), typeof(NoteAttribute));
-
What does Attribute.GetCustomAttributes return?
- A Type object
- A MethodInfo
- A bool
- An attribute array
Show answer
An attribute array — Correct. GetCustomAttributes returns an attribute array.
Next lesson: Named and positional parameters