SkillPilotAI

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

C#
var user = new User(    "Asha", "asha@mail.in", "Asha@123");Console.WriteLine($"Login: {user}"); record User(    string Name,    string Email,    string Password);
Output
$ 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.
C#
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}");}
Output
$ dotnet runProgram.cs(2,1): warning CS0618:  'Payments.PayOld(decimal)' is obsolete:  'Use PayUpi instead'Old 499UPI 499

27.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.
C#
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);
Output
$ 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.
C#
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);
Output
$ dotnet runType: UserName = AshaEmail = asha@mail.inPassword = Asha@123

27.6 Fix: read the attribute and mask

C#
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} }}";}
Output
$ 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.
From attribute to action
  1. 1.Compile time: [Sensitive] saved as metadata in the assembly

  2. 2.Run time: obj.GetType() returns the Type

  3. 3.GetProperties() returns the PropertyInfo list

  4. 4.IsDefined / GetCustomAttribute: is the label there?

  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?

C#
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");}
Output
$ dotnet runUser { Name = Asha }ctor runsTrue

The 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.
C#
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.
Output
$ 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

Source generator flow
  1. 1.Add an attribute (partial type + attribute)

  2. 2.Build time: a compiler plugin (generator) reads it

  3. 3.It generates normal C# code

  4. 4.Run time: no reflection needed, AOT safe

Seen already with [GeneratedRegex]; JSON and logging use the same pattern

PointReflectionSource generator
When the work happensRun timeBuild time
SpeedSlower, cache the resultsFast, plain generated code
Native AOT / trimmingWarnings like IL2075Safe
EffortEasy to writeAdvanced 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

  1. Check for a built-in attribute first (like Obsolete).
  2. Name custom attributes ...Attribute and limit targets with AttributeUsage.
  3. Cache reflection results.
  4. 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.