Reflection

Reflection is a program reading its own metadata: the types, the members, the attributes. The same information is in the assembly, and the runtime exposes it as objects of System.Reflection. A serializer, a dependency injection container and a test runner are all built on it; the page on how to find out the type of a variable shows the shortest use of it.

A Type object

typeof(T) gives the Type at compile time and obj.GetType() at run time. Both point at one object per type, so the two compare equal:

var type = typeof(Order); Console.WriteLine($"name {type.Name}"); Console.WriteLine($"full {type.FullName}"); Console.WriteLine($"class {type.IsClass}"); var order = new Order(2, 3m); var instanceType = order.GetType(); Console.WriteLine($"gettype {instanceType == typeof(Order)}"); sealed class Order { public Order(int quantity, decimal price) { Quantity = quantity; Price = price; } public int Quantity { get; } public decimal Price { get; } public decimal Total => Quantity * Price; public string Describe() => $"{Quantity} at {Price}"; }

dotnet run

name Order
full Order
class True
gettype True

FullName is Order and not Program+Order because the class is declared inside the top-level file with no namespace; a nested class of a named class shows the outer name and a plus sign. The equality is reference equality of one cached object, not a comparison of names.

Methods and properties

GetMethods returns every public method, including the property accessors, which are methods named get_ and set_. DeclaredOnly keeps the inherited ones out, and the program sorts the names so the output is stable:

using System.Reflection; var methods = typeof(Order) .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Select(m => m.Name) .Order(); Console.WriteLine($"methods {string.Join(",", methods)}"); var property = typeof(Order).GetProperty("Total")!; var order = new Order(2, 3m); Console.WriteLine($"total {property.GetValue(order)}"); sealed class Order { public Order(int quantity, decimal price) { Quantity = quantity; Price = price; } public int Quantity { get; } public decimal Price { get; } public decimal Total => Quantity * Price; public string Describe() => $"{Quantity} at {Price}"; }

dotnet run

methods Describe,get_Price,get_Quantity,get_Total
total 6

Four methods were declared and the compiler wrote the three accessors, so the class shows four names of its own. GetValue called the getter and returned the decimal 6, which is the computed Total. The null-forgiving mark after GetProperty says the program knows the property exists; a lookup of a name that is not there returns null, which is the value to check in code that reads a name from a file.

Creating and calling

A constructor is a ConstructorInfo, and Invoke takes the arguments as an object[]. This is how a container creates a type whose name came from configuration:

using System.Reflection; var constructor = typeof(Order).GetConstructor(new[] { typeof(int), typeof(decimal) })!; var made = (Order)constructor.Invoke(new object[] { 4, 5m }); Console.WriteLine($"made {made.Total}"); var describe = typeof(Order).GetMethod("Describe")!; Console.WriteLine($"called {describe.Invoke(made, null)}"); sealed class Order { public Order(int quantity, decimal price) { Quantity = quantity; Price = price; } public int Quantity { get; } public decimal Price { get; } public decimal Total => Quantity * Price; public string Describe() => $"{Quantity} at {Price}"; }

dotnet run

made 20
called 4 at 5

The constructor received the two boxed arguments, and the method received the instance and no arguments. An argument of the wrong type throws ArgumentException at the call, not at compile time, which is the price of reflection: every mistake is a run-time exception. The call is also slower than a direct one, because the runtime checks the arguments and boxes the value types.

The assembly

Assembly.GetTypes lists every type of a file, and Activator.CreateInstance creates one from a Type and its arguments:

using System.Reflection; var assembly = typeof(Program).Assembly; Console.WriteLine($"name {assembly.GetName().Name}"); Console.WriteLine($"version {assembly.GetName().Version}"); var types = assembly.GetTypes() .Where(t => t.IsClass && !t.IsAbstract && !t.Name.StartsWith('<')) .Select(t => t.Name) .Order(); Console.WriteLine($"types {string.Join(",", types)}"); var made = Activator.CreateInstance(typeof(Order), 2, 5m)!; Console.WriteLine($"made {made.GetType().Name}"); sealed class Order { public Order(int quantity, decimal price) { Quantity = quantity; Price = price; } public int Quantity { get; } public decimal Price { get; } }

dotnet run

name Program
version 1.0.0.0
types Order,Program
made Order

The assembly is named after the project, and the two classes are the generated Program and Order; the compiler also writes a closure class with a name that starts with a bracket, which the filter removes. The version 1.0.0.0 is the default of a project with no version property, which the lesson on the project file can change. Reflection over a whole assembly is what a plugin loader does: it reads every type, finds the ones that implement an interface, and creates them by name.

Exercises

  1. Print every property of Order with its type.
  2. Call Describe with a null argument and read the exception.
  3. Find the type of the assembly whose name is a parameter of the program and create it.
  4. Print the interfaces of List<int> and find IList<T> in the list.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which call gives the Type of an object at run time?

    Answer

    obj.GetType()

    typeof takes a type name; GetType is the run-time method.

  2. What does typeof(Order) give?

    Answer

    The Type object of Order

    It is resolved at compile time and returns the cached Type.

  3. What does this program print? Console.WriteLine(typeof(string).Name);

    Answer

    String

    The Name property is the short name of the type.

  4. What does GetMethods return?

    Answer

    An array of MethodInfo

    The program selected the Name of each entry.

  5. What does this program print? Console.WriteLine(typeof(int).IsValueType);

    Answer

    True

    int is a value type, so the property is true.

  6. What does MethodInfo.Invoke do?

    Answer

    Calls the method with the instance and the argument array

    The measured call passed the instance and null for no arguments.

  7. What does this program print? Console.WriteLine(typeof(List<int>).IsGenericType);

    Answer

    True

    The type was built from a generic definition, so it is generic.

  8. What does Assembly.GetTypes return?

    Answer

    Every type of the assembly

    The measured program listed Order and Program from it.

  9. What does GetProperty return for a name that does not exist?

    Answer

    null

    The caller checks it, which is why the program wrote the null-forgiving mark.

  10. Why is a reflected call slower than a direct one?

    Answer

    The runtime checks the arguments and boxes the values

    The type information is used at run time instead of being fixed by the compiler.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev