Reflection

Types, members, assemblies and documentation at run time - System.Type, System.Reflection and Assembly.

Last updated 7 min read Edit on GitHub

On this page

A program can look at its types while it runs: their names and kinds, their fields, properties, methods and constructors, the attributes written on them, their documentation, and the assemblies they come from. It can also make objects and call methods of a type it only knows by name.

Reflection costs nothing until a program uses it. The compiler describes the program's types only when some code says typeof(…) or calls GetType(), and it adds each part (members, assemblies, documentation) only when the program asks for that part.

The core library's own types (System.Console, System.Collections.List<T>…) have their members described when the program names them: with typeof(Console), or by name with a string literal, Type.Find("System.Console") or assembly.GetType("System.Console"). A name computed while the program runs may be any type's, so then every type has its members described, and the program is larger. The program's own types always have them.

Types

typeof(T) and x.GetType() give a Type (namespace System); the same type always gives the same object, so two of them compare with ==.

Member What it gives
Name, Namespace, FullName List, System.Collections, System.Collections.List<System.Int32>.
IsClass, IsValueType, IsInterface, IsEnum, IsPrimitive, IsArray, IsAbstract, IsSealed, IsPublic, IsGenericType… The type's kind.
BaseType, GetInterfaces(), GetGenericArguments(), GetElementType() The types it is made from.
IsSubclassOf(t), IsAssignableFrom(t), IsInstanceOfType(x) How types relate.
GetFields(), GetProperties(), GetMethods(), GetConstructors() and the singular forms (GetMethod("Area")) Its members (see below). BindingFlags picks instance or static, public or not, declared only.
GetCustomAttributes(), IsDefined(typeof(A)) The attributes written on it.
Documentation Its /// documentation, or null.
Assembly The assembly that declares it (null for arrays, pointers, nullables and functions).
Type.Find("Shop.Order") A type of the program by its full name, or null.

A generic type has a Type for each of its instances (typeof(List<i32>)), not one for the generic definition: Type.Find and Assembly.GetTypes() do not give generic types.

Members

The member classes are in System.Reflection. Each has Name, DeclaringType, IsPublic, IsStatic, its attributes and its Documentation.

Class What it does
FieldInfo FieldType; GetValue(target) and SetValue(target, value) (null as the target of a static field).
PropertyInfo PropertyType; GetValue and SetValue, through its accessors.
MethodInfo ReturnType, GetParameters(); Invoke(target, arguments) (null arguments for a method that takes none).
ConstructorInfo GetParameters(); Invoke(arguments) makes an object (null for no arguments).
ParameterInfo Name, ParameterType, Position, its attributes.
Activator CreateInstance(type) and CreateInstance(type, arguments): an object through a public constructor.

Values go in and come out as any?: a number or a value type is boxed, and a value of the wrong type is an InvalidCastError. A member that is not there is a MissingMemberError.

Assemblies

Assembly (namespace System.Reflection) is a library the program was built with, or the program itself.

Member What it gives
Assembly.Loaded The program's assemblies: System.Core, each library it was built with, the program, and the plugins it loaded.
Assembly.Entry The program itself (its project's name).
Assembly.Named("Shapes") One of them by name, or null.
Assembly.Load(path), Assembly.TryLoad(path) A plugin loaded while the program runs (see below).
Location Where a plugin was loaded from (empty for the others).
Name, Version, FullName, IsEntry Shapes, 1.0, Shapes, 1.0.
GetTypes(), GetExportedTypes() The types it declares (nested ones too), and the public ones.
GetType("Shapes.Circle") One of its types by full name, or null.
GetCustomAttributes() The attributes written on the assembly.

A library compiled apart (larva lib, named in DEPS with assembly:) is an assembly of its own. A project named with proj: is compiled with the program, so its types are the program's.

Loading plugins

A program can load, while it runs, an assembly it was not built with: a plugin. Assembly.Load(path) loads it and gives its Assembly, which joins Assembly.Loaded; its types are then found with Type.Find and used through reflection, and its objects are the program's own.

A plugin is a project of type: plugin. larva build makes it a DLL (bin/NAME.dll) that runs on the runtime of the program that loads it, so the two share everything:

  • One heap and one collector. Objects of the plugin and of the program refer to each other freely, and the collector sees all of them.
  • The libraries they were both built with. A plugin built against a library the program also uses (named with assembly: in both projects' DEPS) shares its types: a plugin's class can implement that library's interfaces and derive from its classes, and the program uses the plugin's objects as those types (is, casts, interface and virtual calls), and catches the plugin's exceptions by the library's classes.
  • The libraries' statics. A static field of a library's type is the same field in the program and in its plugins, with the initial value it is declared with, so typeof(T) is the same Type on both sides. A library that only the plugin is built with keeps its statics in the plugin.

The library they share is a Larva library: one larva lib writes. A project of type: library builds a DLL for other languages instead.

Antril
// The library both use (larva lib -o Contract.dll Contract.ant)
into namespace Contract
{
	public interface IGreeter { Greet(str who) : str; }
}
Antril
// The plugin (project.queen: type: plugin, DEPS assembly: ../Contract.dll)
import System;
import Contract;

into namespace Hello
{
	/// Greets in Spanish.
	public class Spanish : IGreeter
	{
		public:
			new() { }
			Greet(str who) : str => "hola " + who;
	}
}
Antril
// The program (DEPS assembly: ../Contract.dll)
import System;
import System.Reflection;
import Contract;

Main()
{
	Assembly hello = Assembly.Load("plugins/Hello.dll");
	if (Type.Find("Hello.Spanish") is Type spanish && Activator.CreateInstance(spanish) is IGreeter greeter)
		Console.WriteLine(greeter.Greet("ana"));
}

A program that calls Assembly.Load or Assembly.TryLoad, in its own code or in a library it is built with (an engine that loads its mods), is built for this (on the shared runtime, larva_rt.dll, copied next to it); other programs are built as always. Loading the same plugin again gives the same assembly. Assembly.Load throws an AssemblyLoadError when the file is not there, is not a plugin, or was built for another runtime or System.Core (another version of Larva, or another gc:); Assembly.TryLoad gives null instead. A plugin's own static constructors run when it loads; the libraries' already ran in the program.

Plugins are native code for Windows: the interpreter and WebAssembly load none. A plugin stays loaded until the program ends.

Documentation

The /// lines written before a type or a member are its documentation: Documentation gives them as one text (lines joined by a line break), or null when there are none.

AntrilRun
import System;
import System.Reflection;

into namespace Shapes
{
	/// A circle of a radius.
	public class Circle
	{
		public:
			/// The radius.
			f64 Radius;
			new() { Radius = 2.0; }
			/// Three times the radius squared.
			Area() : f64 => 3.0 * Radius * Radius;
	}

	Main()
	{
		loop (Assembly a in Assembly.Loaded)
			Console.WriteLine(a.FullName + " " + a.GetTypes().Length);
		if (Type.Find("Shapes.Circle") is Type circle && circle.GetMethod("Area") is MethodInfo area)
		{
			Console.WriteLine(circle.Documentation ?? "-");
			Console.WriteLine(area.Name + ": " + (area.Documentation ?? "-"));
			any made = Activator.CreateInstance(circle);
			Console.WriteLine(area.Invoke(made, []) is f64 value ? value : -1.0);
		}
	}
}
Terminal
larva run
System.Core, 1.0 156
Shapes, 1.0 1
A circle of a radius.
Area: Three times the radius squared.
12

Was this page helpful?

No address is stored; your user name is, if you are signed in.

Esc