Skip to content

Attributes and Reflection

The Course
•
25 min study

Serializers, test frameworks and web frameworks all do something that looks like magic: they find your classes and call your methods without being told. They use reflection, a program's ability to inspect its own types at run time, and attributes, labels attached to code. Knowing how it works demystifies many libraries.

Inspecting a type

typeof(T) gives a Type, and GetType() gives the type of an object. From there, you can list properties and methods, and read or call them by name. This is slower than a direct call, and the compiler can't check any of it.

Looking inside C#
var book = new Book("Dune", 412);
Type type = book.GetType();

Console.WriteLine(type.Name);

foreach (var property in type.GetProperties().OrderBy(property => property.Name))
{
    Console.WriteLine($"{property.Name}: {property.PropertyType.Name} = {property.GetValue(book)}");
}

Console.WriteLine(typeof(Book).IsAssignableTo(typeof(IEquatable<Book>)));

record Book(string Title, int Pages);
Check your prediction
Text
Book
Pages: Int32 = 412
Title: String = Dune
True

Attributes

An attribute is a class that derives from Attribute, attached with square brackets. By itself, it does nothing. It's data waiting for something to read it. [AttributeUsage] restricts where it's allowed. Here's a tiny validator, the same approach used by System.ComponentModel.DataAnnotations.

A validator driven by attributes C#
#nullable enable

using System.Reflection;

Console.WriteLine(string.Join("; ", Validator.Check(new Signup("", 15))));
Console.WriteLine(Validator.Check(new Signup("Ana", 30)).Count);

record Signup([property: NotBlank] string Name, [property: AtLeast(18)] int Age);

[AttributeUsage(AttributeTargets.Property)]
class NotBlankAttribute : Attribute;

[AttributeUsage(AttributeTargets.Property)]
class AtLeastAttribute(int minimum) : Attribute
{
    public int Minimum { get; } = minimum;
}

static class Validator
{
    public static List<string> Check(object target)
    {
        var problems = new List<string>();
        foreach (PropertyInfo property in target.GetType().GetProperties())
        {
            object? value = property.GetValue(target);
            if (property.GetCustomAttribute<NotBlankAttribute>() is not null && string.IsNullOrWhiteSpace(value as string))
            {
                problems.Add($"{property.Name} is blank");
            }
            if (property.GetCustomAttribute<AtLeastAttribute>() is { } least && value is int number && number < least.Minimum)
            {
                problems.Add($"{property.Name} is under {least.Minimum}");
            }
        }
        return problems;
    }
}
Check your prediction
Text
Name is blank; Age is under 18
0

[property: ...] applies an attribute to the generated property of a record, rather than to the constructor's parameter.

Finding and calling methods

Test frameworks find methods with an attribute, then call them. Here's most of a test runner in a few lines. Note that an exception from a method called through reflection arrives wrapped in TargetInvocationException, with the original in InnerException.

A tiny test runner C#
using System.Reflection;

var methods = typeof(MathTests).GetMethods().Where(method => method.GetCustomAttribute<TestAttribute>() is not null).OrderBy(method => method.Name);

foreach (MethodInfo method in methods)
{
    try
    {
        method.Invoke(new MathTests(), null);
        Console.WriteLine($"pass {method.Name}");
    }
    catch (TargetInvocationException e)
    {
        Console.WriteLine($"FAIL {method.Name}: {e.InnerException?.Message}");
    }
}

[AttributeUsage(AttributeTargets.Method)]
class TestAttribute : Attribute;

class MathTests
{
    [Test]
    public void Adds()
    {
        if (1 + 1 != 2)
        {
            throw new Exception("wrong sum");
        }
    }

    [Test]
    public void Fails()
    {
        throw new Exception("always");
    }

    public void NotATest()
    {
        throw new Exception("never called");
    }
}
Check your prediction
Text
pass Adds
FAIL Fails: always

Costs, and the modern alternative

Reflection has real costs. It's much slower than a direct call. And trimming and ahead-of-time compilation, which .NET uses to make small, fast-starting programs, may remove code that only reflection uses. So the modern choice is a source generator, which writes ordinary C# at compile time. System.Text.Json offers one, and [GeneratedRegex] is another. Use reflection for tools and startup work, not for each record in a hot loop.

Regex in passing

[GeneratedRegex] shows attributes doing useful work: on your computer, a source generator reads the attribute and writes the matching code at compile time. This browser's compiler doesn't run source generators, so that form gives error CS8795 here. The regular Regex class gives the same results, and it's fine for most code.

The Regex class C#
using System.Text.RegularExpressions;

var plain = new Regex(@"^(\d{4})-(\d{2})$");
Match match = plain.Match("2026-11");
Console.WriteLine(match.Success);
Console.WriteLine(match.Groups[2].Value);

Console.WriteLine(Regex.Matches("two words", @"\w+").Count);
Check your prediction
Text
True
11
2

Your turn

Exercise

A simple serializer

Write Describe(object target), using reflection. It returns the public properties of an object as name=value pairs joined with , , sorted by name. A property with [Hidden] is left out, and a property with [Label("Pages")] uses that text as its name. A null value prints as null.

Print the result for a record Book(string Title, int Pages, string? Secret, string? Note), with the Pages property labelled Length, the Secret property hidden, and Note null.

When it works, it prints:

Text
Length=412, Note=null, Title=Dune
Your workspace C#
#nullable enable

using System.Reflection;

Console.WriteLine(typeof(string).Name);
Hint 1: the idea

Each property goes through the same small steps: skip it if hidden, choose the name, read the value. A LINQ chain fits that well.

Hint 2: a first step

Declare the two attribute classes, then print each property's name and value with no attributes applied. Remember [property: ...] for a record's parameters.

Show one solution
C#
#nullable enable

using System.Reflection;

var book = new Book("Dune", 412, "hidden", null);
Console.WriteLine(Describe(book));

static string Describe(object target)
{
    var pairs = target.GetType().GetProperties()
        .Where(property => property.GetCustomAttribute<HiddenAttribute>() is null)
        .Select(property => (Name: property.GetCustomAttribute<LabelAttribute>()?.Text ?? property.Name, Value: property.GetValue(target)))
        .OrderBy(pair => pair.Name)
        .Select(pair => $"{pair.Name}={pair.Value ?? "null"}");
    return string.Join(", ", pairs);
}

record Book(string Title, [property: Label("Length")] int Pages, [property: Hidden] string? Secret, string? Note);

[AttributeUsage(AttributeTargets.Property)]
class HiddenAttribute : Attribute;

[AttributeUsage(AttributeTargets.Property)]
class LabelAttribute(string text) : Attribute
{
    public string Text { get; } = text;
}
Text
Length=412, Note=null, Title=Dune

Was this article helpful?

Your response is saved on this device.