Skip to content
Tutorials Center
My learning

Topics

Lesson 122 of 182 ยท Standard Library

Reflection and Attributes

Learn C# reflection: typeof and GetType, reading properties and methods, Activator, custom attributes, generic types, performance costs and source generators.

Normally the compiler knows every type your program uses. You write person.Name and the compiler checks that Person has a Name property. Reflection turns this around: at run time your code can look at a type it has never seen, list its properties and methods, read and write values, create objects and call methods by name. It is how serializers turn any object into JSON, how test frameworks find your test methods, how dependency injection containers build objects, and how ORMs map classes to tables.

Reflection is powerful and a little dangerous. It bypasses compile-time checking, it is slower than normal code and it interacts badly with trimming and Native AOT. This lesson shows what reflection can do, builds a tiny attribute-driven validator with it, explains the costs and finishes with the modern alternative, source generators. You should know classes, properties and generics before you start.

Types as objects: typeof and GetType

Every type in .NET has a System.Type object that describes it. You get one in two ways: typeof(T) when you know the type at compile time, and obj.GetType() when you have an object and want its actual (runtime) type.

C# typeof and GetType

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

shape is declared as Shape but the object is a Circle; GetType() reports the real type, which is why Name prints Circle. Generic types have unusual names: List`1 means "List with one type parameter", and typeof(List<>) (empty angle brackets) names the open generic type. Use IsAssignableFrom, or simply is, to ask "can this value be used as that type?" Remember that the C# operators is and as are faster and clearer when you know the type at compile time; reflection is for when you do not.

Inspecting members

A Type can list its properties, fields, methods and constructors through GetProperties(), GetFields(), GetMethods() and GetConstructors(). By default you get only public members. Pass BindingFlags to ask for others (private, static, inherited ones).

C# Listing members

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice the backing fields: the compiler hides the field behind Name and Stock and names it <Name>k__BackingField, which only shows up with NonPublic. Look at p.CanWrite: Stock has a private setter, so CanWrite is true even though outside code cannot call it; use p.SetMethod?.IsPublic for that question. !m.IsSpecialName filters out the compiler-generated get_ and set_ accessors, which are also methods.

Reflection can read private members. That is useful for debugging tools and serializers, but it also means private is a convention for code, not a security boundary. In partial-trust or locked-down environments, the runtime may block it, and in trimmed or Native AOT apps the members may not exist at all.

Reading, writing and calling by name

PropertyInfo.GetValue and SetValue, FieldInfo.GetValue and MethodInfo.Invoke let you work with members you only know by name. All of them use object, so you box and cast.

C# GetValue, SetValue and Invoke

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two traps are visible here. First, a type mismatch is only found when the line runs (ArgumentException), so you lose the safety net that C# usually gives you. Second, MethodInfo.Invoke wraps any exception from the target method in a TargetInvocationException; always look at InnerException, or you will log a useless message.

Creating objects with Activator

Activator.CreateInstance builds an object from a Type. Use it when the concrete class is only known at run time, for example when it comes from a configuration file or a plugin. A ConstructorInfo gives finer control over which constructor to call.

C# Activator and ConstructorInfo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Most of the time you do not need Activator yourself. If you want pluggable objects, prefer dependency injection or a factory delegate such as Func<T>; they are type-safe and faster. Reflection-created objects are a good fit for tooling and frameworks.

Attributes: metadata you attach to code

An attribute attaches extra information to a type, method, property, parameter or assembly. You have already used some: [Flags] on an enum, [Obsolete] on a method, [Required] on a model property. An attribute does nothing by itself. Another piece of code, the compiler or your own reflection code, has to read it and act on it.

You create an attribute by writing a class that derives from System.Attribute. The convention is to end the name with Attribute; in square brackets you may leave that suffix off. [AttributeUsage] says where the attribute may be placed.

C# A custom attribute and a validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

That is the same idea behind System.ComponentModel.DataAnnotations, ASP.NET Core model validation and test attributes like [Fact]. Look at the pieces: the attribute class stores plain data (constructor arguments are the positional parameters, Message = "..." sets a named property), and GetCustomAttribute<T>() creates the attribute object on demand and returns null when it is absent. The pattern is { } range both tests for null and names the result.

Attributes can be read from any reflection object: Type, MethodInfo, PropertyInfo, ParameterInfo, Assembly. Use GetCustomAttributes<T>() if a member can carry several (set AllowMultiple = true in AttributeUsage), and IsDefined(typeof(T)) when you only need a yes or no.

Attribute arguments must be compile-time constants (strings, numbers, enums, typeof(...) and arrays of those), so you cannot pass a DateTime or a lambda. Compilers also understand special attributes such as [CallerMemberName], [NotNullWhen], [MethodImpl] and [Conditional]; these influence compilation without reflection at run time. Chapter analyzers and style covers some of them.

Built-in attributes worth knowing

The framework ships many attributes. These are the ones you meet most often:

Attribute Placed on What it does
[Flags] enum Marks an enum as a set of bit flags, so ToString() prints Read, Write instead of a number.
[Obsolete("message", error)] any member Makes the compiler warn (or fail when error is true) at every use.
[Serializable] class, struct Legacy marker for binary serialization. BinaryFormatter is removed in modern .NET, so new code uses System.Text.Json and does not need it.
[NonSerialized] field Legacy: excludes a field from binary serialization. Use [JsonIgnore] with System.Text.Json.
[ThreadStatic] static field Gives every thread its own copy of the field. Initializers run only for the first thread, so prefer ThreadLocal<T>.
[DllImport] / [LibraryImport] extern method Calls a function in a native library; see unsafe code and interop.
[Conditional("DEBUG")] method Calls to the method are removed by the compiler unless the symbol is defined.
[CallerMemberName] optional parameter The compiler fills in the name of the calling member.
[AttributeUsage] attribute class Limits where an attribute may be placed and whether it may repeat.
C# Flags and Obsolete

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

For a fuller catalog see the built-in attributes reference.

Discovering types across an assembly

Frameworks find plugins, handlers, tests and controllers by scanning an assembly for types with a given attribute or interface. Assembly.GetExecutingAssembly().GetTypes() returns every type, including the compiler-generated ones, so filter carefully.

C# Scanning for handlers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

BrokenHandler is skipped because it is abstract and cannot be instantiated. This "scan and register" pattern is how many frameworks wire themselves up, and it is exactly the part that breaks in trimmed apps: the trimmer cannot see that StopHandler is needed when nothing refers to it by name.

What reflection costs

Reflection is slower than normal code for three reasons: lookups by name are string searches, calls go through object boxing and argument arrays, and the JIT cannot inline them. How much slower depends on the case; calling a method through MethodInfo.Invoke is often tens of times slower than a direct call, though the absolute cost is still microseconds. That is fine for startup scanning, and unacceptable inside a tight loop.

The standard remedies, from simple to advanced:

  1. Cache the metadata. GetProperty("Name") does a search every time. Do it once and keep the PropertyInfo in a static dictionary.
  2. Turn reflection into delegates. Delegate.CreateDelegate, or compiled expression trees, build a fast typed delegate once and then call it at near-native speed.
  3. Generate code instead. A source generator inspects your code at compile time and writes the boilerplate (for example the serialization code for each type) before the program is built. There is no run-time lookup, and it works with trimming and Native AOT. System.Text.Json offers this through JsonSerializerContext (JSON lesson), and logging, regular expressions and many DI libraries do the same. Writing your own generator needs Roslyn APIs and is a topic for the source generators lesson.
C# Caching reflection results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The three calls to Read search only twice; the third hits the cache. For serious hot paths, benchmark with a real tool (BenchmarkDotNet is a NuGet package and not available here) instead of trusting a stopwatch.

When to use reflection, and when not to

Use reflection when:

  • you build frameworks or tools (serializers, mappers, test runners, DI containers, plugin loaders);
  • types are only known at run time (configuration, plugins);
  • you need metadata from attributes.

Avoid it when:

  • an interface, generic method or delegate would do the job with compile-time checking;
  • the code sits in a hot loop;
  • you target Native AOT or trimming (use source generators or annotate with [DynamicallyAccessedMembers] so the trimmer keeps what you need);
  • you are tempted to call private members of somebody else's library. That breaks on the next update.

Never create types or call methods whose names come from untrusted input, such as Type.GetType(userText) followed by Activator.CreateInstance. An attacker can make your program instantiate any class available to it. Restrict lookups to an allow-list of known types.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given Shape s = new Circle(1); what does s.GetType().Name return?

    GetType returns the actual runtime type of the object. typeof(Shape) would give the declared type, but the object itself is a Circle.
  2. 2. A method called with MethodInfo.Invoke throws an InvalidOperationException. What does your calling code catch?

    Invoke wraps exceptions from the target in a TargetInvocationException. Read InnerException to find the real problem.
  3. 3. Which statement about attributes is true?

    An attribute only stores information. Something must read it, either the compiler or your own reflection code. Arguments must be compile-time constants.
  4. 4. What is the best way to make repeated reflection lookups cheaper?

    Name lookups are the costly part, so do them once. A typed delegate created from the getter is even faster than PropertyInfo.GetValue.
  5. 5. Why are source generators preferred over reflection in Native AOT apps?

    Generated code is ordinary code that the compiler and trimmer can analyze. Reflection looks things up dynamically, which the trimmer cannot always foresee.

Summary

  • typeof(T) and obj.GetType() give you a Type object that describes a type at run time.
  • GetProperties, GetMethods, GetFields and GetConstructors list members; BindingFlags selects non-public, static or declared-only members.
  • GetValue, SetValue and Invoke work through object, defer type errors to run time and wrap exceptions in TargetInvocationException.
  • Activator.CreateInstance, MakeGenericType and MakeGenericMethod create objects and generic instantiations from Type values.
  • Custom attributes derive from Attribute, take constant arguments and become useful when your code reads them with GetCustomAttribute<T>().
  • Reflection is slower and fragile with trimming; cache MemberInfo objects, build delegates, or use source generators instead.
  • Never feed untrusted text into Type.GetType.

Next: Expression Trees and Dynamic