Attributes and reflection
Attributes and reflection
Reflection reads type and member information from compiled metadata at runtime. Attributes attach declarative information to code. An attribute is not automatically a validation rule or an action: some compiler, framework or application must interpret it.
Examples target the proposed C# 14 / .NET 10 console baseline (one independent Program.cs per example, nullable enabled). Expected outputs are reasoned, not executed. Source-generation examples require the standard SDK and its built-in generators; no extra packages or external services are used.
Inspect a known data type
typeof obtains a Type for a named type. GetProperties returns property metadata; it does not read property values. Explicitly sort names for reproducible output.
using System;using System.Linq;using System.Reflection;foreach (var property in typeof(StockItem) .GetProperties(BindingFlags.Public | BindingFlags.Instance) .OrderBy(p => p.Name, StringComparer.Ordinal)) Console.WriteLine($"{property.Name}: {property.PropertyType.Name}");sealed class StockItem{ public string Code { get; set; } = "A1"; public int Quantity { get; set; }}The metadata describes declared property types. No StockItem instance is required.
Expected output (reasoned, not executed):
Code: StringQuantity: Int32Read attribute arguments without constructing attributes
CustomAttributeData exposes metadata about an attribute application without executing its constructor. The declared argument may differ from a value a constructor would compute.
using System;using System.Linq;using System.Reflection;var entry = CustomAttributeData.GetCustomAttributes(typeof(StockItem)) .Single(a => a.AttributeType == typeof(LabelAttribute));Console.WriteLine(entry.ConstructorArguments[0].Value);[Label("inventory")]sealed class StockItem { }[AttributeUsage(AttributeTargets.Class)]sealed class LabelAttribute : Attribute{ public LabelAttribute(string name) { Name = name; } public string Name { get; }}The metadata contains the literal inventory. Reading actual attribute instances can invoke their constructors; this fixture does not.
Expected output (reasoned, not executed):
inventoryInspect a closed generic type
A constructed generic type has actual type arguments; its generic type definition describes the parameterized type before arguments are supplied. Reflection is useful when generic types are selected at runtime.
using System;using System.Collections.Generic;Type actual = typeof(List<int>);Console.WriteLine(actual.IsGenericType);Console.WriteLine(actual.GetGenericTypeDefinition() == typeof(List<>));Console.WriteLine(actual.GetGenericArguments()[0].Name);The generic definition is List<> and the concrete argument is Int32.
Expected output (reasoned, not executed):
TrueTrueInt32Common mistakes and edge cases
Reflection is not a security sandbox. Activator.CreateInstance may invoke a constructor, PropertyInfo.GetValue may invoke a getter, and MethodInfo.Invoke executes code. Use only reviewed types and allowlisted choices, not arbitrary type names or assemblies supplied by users. Prefer direct calls when types are known. dynamic defers some binding to runtime; it is not the same as reflecting over metadata.
Practice and recap
Add a bool Available property to StockItem in example 1. Predict the order and types. Explain why no object needs to be constructed.
Hint: Sort names using ordinal comparison.
Learning objective: Read known metadata without executing arbitrary plugins. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Attributes and reflection — knowledge check
Apply the lesson concepts to the following scenarios.
What does typeof(StockItem) return?
What does GetProperties return?
Which API reads declared attribute arguments without creating the attribute instance?
What is the generic definition of List<int>?
Why avoid invoking unknown members?