Skip to content

1.23 — Attributes and Reflection

← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.22 Anonymous types, dynamic, var · Next: 1.24 Partial classes and local functions

Markers: ⭐ · Confidence: 🔴 · Last reviewed: —


TL;DR

  • An attribute is a label you attach to code. On its own it does nothing — something has to go looking for it.
  • Reflection is code inspecting types at runtime: finding attributes, reading properties, calling methods by name.
  • Reflection is slow and unsafe at compile time. Cache what you look up, and prefer source generators when you can.

The concept

An attribute is a sticky note on your code.

[Required]
public string Name { get; set; }

That [Required] does absolutely nothing by itself. It does not validate anything. It is just a note stored in the compiled file saying "this property has been marked Required".

Something else — the ASP.NET Core validation system — comes along later, looks at the property, finds the note, and acts on it.

Reflection is the mechanism for reading those notes, and more generally for a program to examine itself at runtime: listing a type's properties, finding its methods, creating instances, and calling things by name.

Together they are how a huge amount of ASP.NET Core works. Attributes describe intent; the framework uses reflection to discover it.


How it works

Attributes you already use

[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
    [HttpGet("{id:guid}")]
    [Authorize(Roles = "Admin")]
    [ProducesResponseType<OrderDto>(StatusCodes.Status200OK)]
    public async Task<IActionResult> Get(Guid id) { }
}

public class CreateOrderRequest
{
    [Required]
    [StringLength(100, MinimumLength = 3)]
    public string CustomerName { get; set; } = "";

    [Range(0.01, 100_000)]
    public decimal Total { get; set; }
}

Every one of those brackets is a note. None of them contains logic. The routing system, the authorization system, the validation system and Swagger each read the ones they care about.

Writing your own attribute

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SensitiveAttribute(string reason) : Attribute
{
    public string Reason { get; } = reason;
}

public class Customer
{
    public string Name { get; set; } = "";

    [Sensitive("PII — must be redacted in logs")]
    public string Email { get; set; } = "";
}

Two conventions worth knowing:

  • The class name ends in Attribute, but you leave that off when using it. SensitiveAttribute is written as [Sensitive].
  • [AttributeUsage] controls where it can be applied and whether it can appear more than once. Without it, your attribute can go anywhere, which is rarely what you want.

Reflection — reading the notes

var properties = typeof(Customer).GetProperties();

foreach (var prop in properties)
{
    var sensitive = prop.GetCustomAttribute<SensitiveAttribute>();
    if (sensitive is not null)
        Console.WriteLine($"{prop.Name} is sensitive: {sensitive.Reason}");
}

// Output: Email is sensitive: PII — must be redacted in logs

Other things reflection can do:

var type = typeof(Customer);

type.Name;                                  // "Customer"
type.GetProperties();                       // all public properties
type.GetMethods();                          // all public methods

var instance = Activator.CreateInstance(type);      // create one by type
var instance2 = Activator.CreateInstance<Customer>();

var prop = type.GetProperty("Email");
prop?.SetValue(instance, "a@b.com");        // set a property by name
var value = prop?.GetValue(instance);       // read it back

var method = type.GetMethod("Validate");
method?.Invoke(instance, null);             // call a method by name

Notice how much of this is string-based. GetProperty("Email") returns null if you misspell it or someone renames the property — no compile error, and rename refactoring will not update the string. That is the fundamental danger of reflection.

The performance problem

Reflection is slow. Roughly speaking, calling a method through reflection is hundreds of times slower than calling it directly, because every call has to look up metadata, check access, and box the arguments.

If you must use it, cache the lookup:

// BAD — does the expensive lookup on every single call
public string GetName(object obj)
    => obj.GetType().GetProperty("Name")?.GetValue(obj)?.ToString() ?? "";

// BETTER — look it up once per type, then reuse
private static readonly ConcurrentDictionary<Type, PropertyInfo?> _cache = new();

public string GetName(object obj)
{
    var prop = _cache.GetOrAdd(obj.GetType(), t => t.GetProperty("Name"));
    return prop?.GetValue(obj)?.ToString() ?? "";
}

The lookup is the expensive part. The invoke is much cheaper. Caching PropertyInfo objects turns a slow operation into a reasonable one.

The modern alternative — source generators

Reflection does its work at runtime. A source generator does the same kind of work at compile time, writing real C# code into your project that the compiler then compiles normally.

That gives you three wins at once: no runtime cost, full compile-time checking, and it works with Native AOT (which trims away unused types, breaking reflection).

This is why modern .NET has been moving away from reflection:

// Source-generated JSON — no reflection at runtime
[JsonSerializable(typeof(Order))]
internal partial class OrderJsonContext : JsonSerializerContext { }

var json = JsonSerializer.Serialize(order, OrderJsonContext.Default.Order);

The same shift has happened for logging ([LoggerMessage]), regular expressions ([GeneratedRegex]), and configuration binding. Mentioning this trend is a good way to show you follow modern .NET. See 21.13.


Code

A realistic use — automatically redacting sensitive fields before logging:

public static class LogSanitizer
{
    // Cache the reflection work per type. Done once, reused forever.
    private static readonly ConcurrentDictionary<Type, PropertyInfo[]> _sensitiveProps = new();

    public static Dictionary<string, object?> ToLogSafeDictionary(object obj)
    {
        var type = obj.GetType();

        var sensitive = _sensitiveProps.GetOrAdd(type, t =>
            t.GetProperties()
             .Where(p => p.GetCustomAttribute<SensitiveAttribute>() is not null)
             .ToArray());

        var sensitiveNames = sensitive.Select(p => p.Name).ToHashSet();

        return type.GetProperties()
            .ToDictionary(
                p => p.Name,
                p => sensitiveNames.Contains(p.Name)
                        ? "***REDACTED***"
                        : p.GetValue(obj));
    }
}

The pattern here is the one to remember: do the reflection once per type and cache it, then the per-call work is just a dictionary lookup.

See 18.10 for why redacting matters.


Interview questions

Q: What is an attribute?

It is metadata attached to code — a class, method, property or parameter. On its own it does nothing at all; it is just information stored in the compiled assembly. Something else has to read it and act on it, usually through reflection. [Required] does not validate anything by itself — ASP.NET Core's validation system finds it and applies the rule. That separation is the whole design: attributes describe intent, and a framework decides what to do about it.

Q: What is reflection and what is it used for?

It is the ability of code to inspect and manipulate types at runtime — listing properties and methods, reading attributes, creating instances, and invoking members by name. It is what makes most frameworks possible. ASP.NET Core uses it to discover controllers and map routes, the DI container uses it to work out constructor parameters, serializers use it to map JSON to properties, and ORMs use it to map rows to entities.

Q: What are the downsides of reflection?

Three main ones. It is slow — a reflective call is orders of magnitude more expensive than a direct one, because of metadata lookup, access checks and boxing. It is not type-safe, since you are usually looking things up by string, so a typo or a rename becomes a runtime failure with no compiler warning. And it breaks with trimming and Native AOT, because the compiler cannot see which types are used and removes them. The mitigations are to cache the metadata lookups, and increasingly to use source generators, which do the equivalent work at compile time with none of the drawbacks.

Q: What is a source generator and how does it relate to this?

It is a compiler plugin that generates real C# source code during compilation, which is then compiled normally. It solves the same problems reflection solves, but at build time — so there is no runtime cost, everything is checked by the compiler, and it works under Native AOT. Modern .NET has been steadily replacing reflection with source generators for JSON serialization, logging, regular expressions and configuration binding.


Traps ⚠️

  • Attributes do nothing by themselves. If nothing reads it, it has no effect. A custom attribute with no handler is a very confusing no-op.
  • Reflection is slow — but the lookup is the slow part. Cache PropertyInfo and MethodInfo; do not re-fetch on every call.
  • String-based lookups break silently on rename. nameof() helps where you can use it.
  • Reflection can reach private members. Convenient in tests, but it means private is not a security boundary.
  • Reflection breaks under trimming and Native AOT. Types that are only referenced reflectively get removed, and you get a runtime failure that never happened in debug.
  • GetCustomAttribute returns a new instance each time by default. Do not rely on reference equality between calls.
  • Attribute arguments must be compile-time constants. You cannot pass a computed value or a DateTime.


Sources