Attributes and reflection
Attributes are labels in square brackets that the compiler stores as metadata; reflection is how running code reads types, properties and those labels. Together they let one generic piece of code (like a safe logger) act on any type, which is exactly how ASP.NET Core routing and xUnit work.
27.1 Why is it used?
- A record's auto-generated ToString prints every property, including secrets like Password.
- Writing a ToString by hand for every type is copy paste, and new secret properties are easy to forget.
- We need a label on the property (attribute) and code that reads it at run time (reflection).
- Frameworks use the same idea: [HttpGet], [Fact], [Obsolete].
27.2 The problem: password in the log
var user = new User( "Asha", "asha@mail.in", "Asha@123");Console.WriteLine($"Login: {user}"); record User( string Name, string Email, string Password);$ dotnet runLogin: User { Name = Asha, Email = asha@mail.in, Password = Asha@123 }27.3 Built-in attribute: Obsolete
- An attribute sits on a class, method or property; the compiler saves it in the assembly as metadata.
- Seen before: [Flags] on an enum, [GeneratedRegex].
- [Obsolete] is read by the compiler itself and produces warning CS0618.
var pay = new Payments();pay.PayOld(499);pay.PayUpi(499); class Payments{ [Obsolete("Use PayUpi instead")] public void PayOld(decimal amount) => Console.WriteLine($"Old {amount}"); public void PayUpi(decimal amount) => Console.WriteLine($"UPI {amount}");}$ dotnet runProgram.cs(2,1): warning CS0618: 'Payments.PayOld(decimal)' is obsolete: 'Use PayUpi instead'Old 499UPI 49927.4 Custom attribute: Sensitive
- A class that inherits from Attribute; by convention the name ends with Attribute, but you apply it as [Sensitive].
- [AttributeUsage(AttributeTargets.Property)] limits where it can be placed.
- [property: Sensitive] on a record parameter puts the label on the generated property.
- The password still prints: nothing reads the label yet.
var user = new User( "Asha", "asha@mail.in", "Asha@123");Console.WriteLine($"Login: {user}"); [AttributeUsage(AttributeTargets.Property)]sealed class SensitiveAttribute : Attribute{} record User( string Name, string Email, [property: Sensitive] string Password);$ dotnet runLogin: User { Name = Asha, Email = asha@mail.in, Password = Asha@123 }27.5 Reflection: inspecting a type
- GetType() returns a Type object with the class name, properties and methods.
- GetProperties() returns a PropertyInfo for every public property.
- GetValue(obj) reads that property's value from an object.
using System.Reflection;var user = new User( "Asha", "asha@mail.in", "Asha@123");Type type = user.GetType();Console.WriteLine($"Type: {type.Name}"); foreach (var p in type.GetProperties()){ var value = p.GetValue(user); Console.WriteLine($"{p.Name} = {value}");} record User( string Name, string Email, string Password);$ dotnet runType: UserName = AshaEmail = asha@mail.inPassword = Asha@12327.6 Fix: read the attribute and mask
public static string Describe(object obj){ Type type = obj.GetType(); var parts = new List<string>(); foreach (var p in type.GetProperties()) { bool hide = p.IsDefined( typeof(SensitiveAttribute)); object? value = hide ? "***" : p.GetValue(obj); parts.Add($"{p.Name} = {value}"); } var body = string.Join(", ", parts); return $"{type.Name} {{ {body} }}";}$ dotnet runUser { Name = Asha, Email = asha@mail.in, Password = *** }Card { Holder = Asha, Number = *** }- IsDefined checks whether [Sensitive] is on the property; if yes, "***" replaces the value.
- Works for any type: Card.Number is masked without writing any extra code for Card.
- Step 1
1.Compile time: [Sensitive] saved as metadata in the assembly
- Step 2
2.Run time: obj.GetType() returns the Type
- Step 3
3.GetProperties() returns the PropertyInfo list
- Step 4
4.IsDefined / GetCustomAttribute: is the label there?
- Step 5
5.Act on it: mask the value with ***
The attribute is only data; the reflection code does the work
27.7 Checkpoint: when does an attribute's constructor run?
using System.Reflection; Console.WriteLine(new User("Asha"));var audit = typeof(User) .GetCustomAttribute<AuditAttribute>();Console.WriteLine(audit is not null); [Audit]record User(string Name); class AuditAttribute : Attribute{ public AuditAttribute() => Console.WriteLine("ctor runs");}$ dotnet runUser { Name = Asha }ctor runsTrueThe attribute object is created only when someone asks for it through reflection (GetCustomAttribute), not when the User is created.
27.8 Performance: reflect once, then cache
- Calling GetProperties and IsDefined on every log call repeats slow work on every request.
- A generic static class LogPlan<T> computes properties and hide flags once per type.
- Every closed generic type is separate, so the cache is automatically per type.
static class LogPlan<T>{ public static readonly PropertyInfo[] Props = typeof(T).GetProperties(); static readonly Type Mark = typeof(SensitiveAttribute); public static readonly bool[] Hide = Array.ConvertAll(Props, p => p.IsDefined(Mark));}27.9 Reflection and Native AOT
- File-based apps are Native AOT ready by default; AOT and trimming remove unused code at build time.
- The compiler cannot know which type's properties will be asked for at run time, hence warning IL2075.
- Reflection-heavy code can be a problem for AOT and serverless.
$ dotnet run SafeLog.csSafeLog.cs(15,23): warning IL2075: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicProperties' in call to 'System.Type.GetProperties()'.User { Name = Asha, Email = asha@mail.in, Password = *** }27.10 The idea: source generators
- Step 1
1.Add an attribute (partial type + attribute)
- Step 2
2.Build time: a compiler plugin (generator) reads it
- Step 3
3.It generates normal C# code
- Step 4
4.Run time: no reflection needed, AOT safe
Seen already with [GeneratedRegex]; JSON and logging use the same pattern
| Point | Reflection | Source generator |
|---|---|---|
| When the work happens | Run time | Build time |
| Speed | Slower, cache the results | Fast, plain generated code |
| Native AOT / trimming | Warnings like IL2075 | Safe |
| Effort | Easy to write | Advanced to write your own |
27.11 Common mistakes
- Thinking an attribute does magic by itself: [Sensitive] changed nothing until SafeLog read it.
- [HttpGet] and [Fact] work only because ASP.NET Core and xUnit read them.
- Running full reflection on every call instead of caching.
- Using reflection on AOT or hot paths where a source generator fits better.
- No need to avoid reflection completely: cache it and use it thoughtfully.
27.12 Rules
- Check for a built-in attribute first (like Obsolete).
- Name custom attributes ...Attribute and limit targets with AttributeUsage.
- Cache reflection results.
- For AOT or hot paths, prefer source generators.
27.13 Interview tips
- Attributes are declarative metadata stored in the assembly; they do not change behaviour by themselves.
- Reflection reads types, properties and attributes at run time (GetType, GetProperties, IsDefined, GetCustomAttribute).
- ASP.NET Core routing and xUnit discover [HttpGet] / [Fact] this way.
- Reflection is slow and AOT-unfriendly: cache results and use source generators where possible.
- Attribute constructors run lazily, only when requested through reflection.