Skip to content
Happy Programming Guide
Start learning
C#

C# Reflection and Attributes

Reading type information at run time, writing custom attributes, and the performance cost — plus source generators as the modern alternative.

Two monitors on a developer desk

Reflection lets a program examine and use type information while it is running — listing a class’s properties, reading an attribute, or calling a method by name. Attributes are the metadata reflection reads. Together they are how serialisers, validators, test runners and dependency injection containers work without knowing your types in advance.

Reading type information#

CSHARP
using System.Reflection;

var product = new Product { Name = "Pen", Price = 1.50m };
Type type = product.GetType();          // or typeof(Product)

Console.WriteLine(type.Name);           // Product
Console.WriteLine(type.FullName);       // MyApp.Models.Product

foreach (var property in type.GetProperties())
{
    Console.WriteLine($"{property.PropertyType.Name} {property.Name} = " +
                      property.GetValue(product));
}
CSHARP
// Reading and writing a property by name
var nameProperty = type.GetProperty("Name");
nameProperty?.SetValue(product, "Pencil");

// Calling a method by name
var method = type.GetMethod("Describe");
var result = method?.Invoke(product, null);

// Creating an instance
var instance = Activator.CreateInstance<Product>();
var other = Activator.CreateInstance(type, "Pen", 1.50m);

None of this is checked at compile time, which is the point and also the risk. A renamed property breaks a reflection call silently, and you find out at run time.

CSHARP
// Use nameof so a rename breaks the build instead
var property = type.GetProperty(nameof(Product.Name));

Built-in attributes#

CSHARP
[Obsolete("Use CalculateTotalAsync instead")]
public decimal CalculateTotal() { }

[Serializable]
public class Order { }

[JsonPropertyName("product_id")]
public int ProductId { get; set; }

[Required, StringLength(120)]
public string Name { get; set; } = "";

An attribute on its own does nothing. It is metadata attached to the compiled code, waiting for something to read it — the compiler for [Obsolete], the JSON serialiser for [JsonPropertyName], the model binder for [Required].

Writing your own#

CSHARP
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class DisplayNameAttribute : Attribute
{
    public string Name { get; }
    public int Order { get; init; }

    public DisplayNameAttribute(string name) => Name = name;
}
CSHARP
public class Product
{
    [DisplayName("Product name", Order = 1)]
    public string Name { get; set; } = "";

    [DisplayName("Price (£)", Order = 2)]
    public decimal Price { get; set; }

    public int InternalId { get; set; }      // no attribute
}

Three conventions worth following. The class name ends in Attribute and you omit that suffix when applying it. [AttributeUsage] restricts where it can go, so a mistake is a compile error. And marking it sealed is a small performance win when it is looked up.

Reading it back#

CSHARP
public static IEnumerable<(string Header, object? Value)> Describe(object item)
{
    return item.GetType()
        .GetProperties()
        .Select(p => (Property: p, Attribute: p.GetCustomAttribute<DisplayNameAttribute>()))
        .Where(x => x.Attribute is not null)
        .OrderBy(x => x.Attribute!.Order)
        .Select(x => (x.Attribute!.Name, x.Property.GetValue(item)));
}
CSHARP
foreach (var (header, value) in Describe(product))
{
    Console.WriteLine($"{header}: {value}");
}
// Product name: Pen
// Price (£): 1.50

That is the whole pattern: mark things up with an attribute, then write one piece of code that works for any type.

A working example: a small validator#

CSHARP
[AttributeUsage(AttributeTargets.Property)]
public abstract class ValidationRuleAttribute : Attribute
{
    public abstract string? Validate(object? value);
}

public sealed class NotEmptyAttribute : ValidationRuleAttribute
{
    public override string? Validate(object? value) =>
        string.IsNullOrWhiteSpace(value as string) ? "must not be empty" : null;
}

public sealed class RangeAttribute : ValidationRuleAttribute
{
    private readonly decimal _min, _max;

    public RangeAttribute(double min, double max)
    {
        _min = (decimal)min;
        _max = (decimal)max;
    }

    public override string? Validate(object? value) =>
        value is decimal d && (d < _min || d > _max)
            ? $"must be between {_min} and {_max}"
            : null;
}
CSHARP
public static Dictionary<string, List<string>> Validate(object item)
{
    var errors = new Dictionary<string, List<string>>();

    foreach (var property in item.GetType().GetProperties())
    {
        foreach (var rule in property.GetCustomAttributes<ValidationRuleAttribute>())
        {
            var message = rule.Validate(property.GetValue(item));
            if (message is null) continue;

            if (!errors.TryGetValue(property.Name, out var list))
            {
                errors[property.Name] = list = new List<string>();
            }
            list.Add(message);
        }
    }
    return errors;
}
CSHARP
public class Product
{
    [NotEmpty] public string Name { get; set; } = "";
    [Range(0.01, 10000)] public decimal Price { get; set; }
}

var errors = Validate(new Product { Name = "", Price = 0 });
// Name: must not be empty
// Price: must be between 0.01 and 10000

Roughly forty lines, and it works for any class. That leverage is why reflection exists.

The performance cost#

CSHARP
// Slow - reflects on every call
foreach (var item in tenThousandItems)
{
    var properties = item.GetType().GetProperties();
}

// Faster - reflect once per type
private static readonly ConcurrentDictionary<Type, PropertyInfo[]> Cache = new();

static PropertyInfo[] PropertiesOf(Type type) =>
    Cache.GetOrAdd(type, t => t.GetProperties());

Reflection is roughly an order of magnitude slower than direct access, and property lookup is the expensive part rather than the value read. Caching the PropertyInfo array removes most of the cost.

For a hot path, compile a delegate once and call that instead:

CSHARP
using System.Linq.Expressions;

static Func<object, object?> CompileGetter(PropertyInfo property)
{
    var instance = Expression.Parameter(typeof(object), "x");
    var cast = Expression.Convert(instance, property.DeclaringType!);
    var access = Expression.Property(cast, property);
    var box = Expression.Convert(access, typeof(object));

    return Expression.Lambda<Func<object, object?>>(box, instance).Compile();
}

After compilation, calls are close to direct property access. Compilation itself is expensive, so cache the result — this is what serialisation libraries do internally.

Source generators, the modern alternative#

A source generator runs at compile time and writes real C# into your build. You get the same “works for any type” leverage with none of the run-time cost, and it survives trimming.

CSHARP
[JsonSerializable(typeof(Product))]
internal partial class AppJsonContext : JsonSerializerContext { }

// Uses generated code, no reflection at run time
string json = JsonSerializer.Serialize(product, AppJsonContext.Default.Product);

System.Text.Json, regular expressions and logging all have generator-based modes now. For new code that needs this kind of leverage, a source generator is usually the better answer.

When to use reflection#

Reasonable: plugin loading, serialisers, test discovery, dependency injection containers, mapping to and from a database, admin tooling that displays arbitrary objects.

Usually a mistake: calling a method by name when you could call it directly, reading a private field to get around encapsulation, or reflecting inside a loop that runs millions of times.

Questions people ask#

How much slower is reflection?

Roughly ten times for a cached property read, and considerably more if you look the property up each time. Cache the metadata, and for hot paths compile a delegate.

Can I read private members?

Yes, with BindingFlags.NonPublic | BindingFlags.Instance. It is occasionally necessary in tests or tooling and is otherwise a sign that the design needs changing rather than circumventing.

Do attributes affect performance on their own?

No. They are metadata in the assembly and cost nothing until something reads them.

Should I use source generators instead?

For new code where the alternative is reflection in a hot path, yes. They are more work to write, and they cost nothing at run time and work with trimming and AOT.

Where to go next#

C# performance, and how to measure reflection's costRead next

Keep reading

C#

C# and ASP.NET Core

Building web applications and APIs with ASP.NET Core: minimal APIs, controllers, dependency injection, middleware, validation and configuration.

5 min read

C#

C# Security

The security work that matters in .NET applications: SQL injection, XSS, secrets, authentication, deserialization, randomness and dependency scanning.

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *