Development documentation · Some APIs may be unreleased Published release →

Guides

Runtime reflection

Import System.Runtime.Reflection.* to execute a small set of operations on runtime-backed System.Introspection descriptors. Introspection itself remains descriptive. These provisional extensions also support the existing bounded JSON object mapper. See the separate Reflection feature page for a walkthrough.

  • TypeInfo.CreateInstance() -> Result<Object, ReflectionError> invokes a public parameterless constructor on a concrete, nongeneric reference class.
  • PropertyInfo.GetValue(receiver: Object?) -> Result<Object?, ReflectionError> invokes a public instance getter and boxes scalar values.
  • PropertyInfo.SetValue(receiver: Object?, value: Object?) -> Result<(), ReflectionError> invokes a public instance setter. It returns completion after the setter finishes.

Use Result propagation when the caller should return the same expected failure. The Type extensions, Property extensions and ReflectionError document the individual contracts.

Values and execution

Properties must be nonindexed and declared on nongeneric reference classes. Development getters also support nongeneric, non-enum value records: the receiver is the exact boxed record, and getter mutations affect that box, not the original unboxed value. Value-record setters remain unsupported. Compatible derived receivers are supported, and ordinary virtual dispatch selects the implementation. Getters and setters execute user code; reflection does not read or overwrite a backing field directly.

Reference values accept compatible objects or null. Scalar values require their exact boxed built-in type. There is no numeric coercion, null-to-default conversion, enum/union value mapping, private binding or static-property support. Getters can return a nongeneric value record as a fresh box, including nested record properties. These limits are narrower than .NET PropertyInfo's binder and indexer overloads. Null is represented by a nullable object result because this API observes existing object storage; it does not prescribe how application or JSON models express absence.

Metadata that is not backed by the current runtime returns UnboundMetadata. Unsupported shapes, access restrictions, missing constructors/accessors and invalid receiver/value arguments return explicit error cases. Failures raised inside a constructor or accessor remain terminal runtime Faults, including allocation and execution limits. Setters may have side effects before a fault; operations are not transactional.

Only the current loaded program is supported. Dynamic loading, separate execution contexts, generic-class invocation remain future work. These extensions do not make every introspection descriptor executable.

Development FunctionTypeInfo.InvokeMethod and TypeInfo.GetMethods expose a synthesized Function Invoke descriptor. It has no declaration index, token or module; optional properties return None. MethodReflectionExtensions.Invoke returns UnboundMetadata for it. Use typed Function invocation to execute a binding. Declared MethodInfo DefinitionIndex and MemberInfo/ParameterInfo metadata now require Optional matching.

Imported artifact access information

The Rust host's metadata_origin::MetadataOrigin adds optional publicly_visible for type origins and member_access for method origins. The former includes all containing types. SourceAccess preserves Public, Private, Assembly, Family, FamilyOrAssembly, FamilyAndAssembly and CompilerControlled. Fields on the wrong kind of origin are rejected. Reflection requires explicit public source access on imported definitions, in addition to runtime checks; older origins lacking these fields are denied. Definitions without source origins use ordinary runtime access. Rust callers constructing MetadataOrigin literals must supply the new optional fields. Newly imported artifacts need the matching runtime. These host/artifact contracts are not additional guest APIs or permissions to bypass normal runtime access checks.

Constructor arguments, methods and fields

ConstructorInfo describes a constructor through MemberInfo identity, accessibility and GetParameters; GetConstructors defaults to public instance declarations. Constructors are not inherited or included in GetMethods. Adding ConstructorInfo extends the closed MemberInfo family: update exhaustive matches.

TypeReflectionExtensions adds CreateInstance(params Object?[]) and CreateInstance<T>(params Object?[]) returning Result<Object, ReflectionError> and Result<T, ReflectionError>. The described type is constructed; T is a checked result view, validated before invoking user code.

MethodReflectionExtensions adds Invoke(Object? receiver, params Object?[] arguments) -> Result<Object?, ReflectionError>. Use null for static methods and a compatible non-null object for instance methods. Void-returning methods produce a successful null. Virtual calls dispatch normally.

FieldReflectionExtensions adds GetValue(Object?) -> Result<Object?, ReflectionError> and SetValue(Object?, Object?) -> Result<(), ReflectionError>. Fields must be public instance or static fields (including readable literals); source read-only and literal fields cannot be assigned. Private helper visibility does not grant permission. New origins retain field_access and field_readonly arrays; old imported fields without those admission flags cannot execute through reflection.

Arguments require exact boxed built-in scalars or assignable references/null. No numeric coercion, optional defaults, byref/out, generic-class execution, custom value payloads or params expansion of the selected target is provided. Multiple compatible constructors return AmbiguousConstructor; none returns MissingConstructor. Invalid method arguments return InvalidArguments. Incompatible T returns InvalidResultType. UnsupportedMethod and UnsupportedField distinguish unsupported metadata shapes. User Faults stay terminal.

Retained constructor invocation

ConstructorReflectionExtensions.Invoke(self: ConstructorInfo, params arguments: Object?[]) -> Result<Object, ReflectionError> invokes the selected constructor directly. Import System.Runtime.Reflection.* and call constructor.Invoke(arguments). Keep the descriptor after startup discovery to avoid overload selection on each call.

This extension supports concrete nongeneric reference classes and value records, including admitted standard union cases and carriers. Arguments accept exact boxed built-in scalars, exact boxed nongeneric value records, or assignable references/null. Values are boxed on return. Construct a union case first, then pass that boxed case to the selected carrier constructor. No implicit boxed case-to-carrier conversion, coercion, enum construction, generic value construction, optional defaults, byref/out arguments or private execution is supplied. The TypeInfo.CreateInstance overloads retain their existing reference-class-only contract.

UnboundMetadata, UnsupportedType, AccessDenied, MissingConstructor and InvalidArguments distinguish validation failures. Argument validation precedes execution; constructor faults remain terminal. Descriptor identity resolves within the current loaded program; access and arguments are rechecked per invocation. This retains constructor selection, not a compiled execution plan. See the tested union construction case.

ConstructorInfo.Invoke(arguments: Sequence<Object?>) copies a dynamic argument collection before using the same retained-constructor invocation contract. This supports cached route bindings without exposing private array-allocation services. The caller controls collection mutation while it is copied. It adds no overload selection or coercion, and provider/constructor Faults remain terminal.

Dynamic managed arrays

ArrayReflection supplies three bounded operations used by independently compiled JSON mapping:

  • GetLength(array: Object) -> int returns vector length.
  • GetValue(array: Object, index: int) -> Object? boxes scalars and preserves references/null.
  • Create(arrayType: TypeInfo, values: Object?[]) -> Object creates a new vector from a runtime-backed array descriptor and copies exact boxed scalars or compatible references.

For example, ArrayReflection.Create(typeof(int[]), [1, 2]) produces a managed Int32 vector. Input element storage is copied; referenced objects retain identity. Operations use ordinary VM type, bounds, allocation and rooting checks. Invalid indexes, wrong boxed types, null array inputs, unbound descriptors and unsupported element types cause terminal runtime Faults; these methods do not return ReflectionError. Supported elements are the runtime's built-in numeric/Boolean/Character scalars and object-reference types, including arrays. Custom structs/unions and multidimensional arrays are unsupported.

Compared with .NET Array, which supplies instance GetValue/GetLength and length-based CreateInstance overloads, this facade takes Object and a vector descriptor because the dynamic caller has no compile-time element type. Initializing from supplied values avoids exposing partially initialized value storage. The cost is a copy and a narrower API; this is not a claim of better performance. A future checked Result API remains possible without exposing the internal RuntimeServices surface. Introspection descriptors alone stay non-executable.

Generic parameter variance

System.Introspection.GenericParameterTypeInfo : TypeInfo represents an unbound type parameter returned by an open definition's GetGenericArguments() or GetGenericArgument(index). Its read-only Variance: GenericVariance property returns Invariant = 0, Covariant = 1 (out) or Contravariant = 2 (in). Missing annotations mean invariant. Parameter identity remains declaring definition plus ordinal; variance is declaration information, not a new type identity.

For example, discover a definition through AssemblyInfo.GetTypes() and match its argument with GenericParameterTypeInfo parameter => parameter.Variance. The executable consumer checks all three values. Closed Producer<Animal> exposes Animal as its argument, not the declaration's parameter. Ordinary ParameterInfo.IsOut remains the method output-argument convention and does not mean covariance.

This follows .NET's placement of variance on generic parameter metadata, with a specialized descriptor and enum instead of the combined GenericParameterAttributes flags. It does not add method generic-definition discovery. Development native assembly/module discovery supports open definitions with explicit reflection-root schema 6 retention: typeCatalogs lists exact assembly identities; the types, moduleCatalogs and moduleFunctions arrays remain required. Retain module names separately through moduleCatalogs when using GetModules. Type-catalog retention does not grant construction or member invocation. Unretained assemblies and foreign module scopes fault. Empty declared modules return empty arrays. Ordinary discovered types still need supported native shapes; open member and relationship queries remain unsupported. No Raven Runtime Contract change is required.

Generic argument sequences

TypeInfo.GetGenericArguments() returns a freshly populated sequence in declaration order, using the same count and indexed handle queries as GenericArgumentCount and GetGenericArgument(index). Nongeneric types return an empty sequence. Argument descriptors retain concrete type identity for constructions and owner/ordinal identity for open parameters; this follows .NET's distinction between a generic definition's parameters and a construction's actual arguments.

The class-library implementation reserves one result array and fills it through RuntimeTypeInfo.FromHandle; it no longer depends on a separate native snapshot binding for this operation. Closed nominal constructions are qualified in interpreter, AOT and managed JIT by the consumer. The sibling open-definition consumer qualifies declaration parameters and variance in interpreter, AOT and managed JIT through explicit type-catalog retention. This does not grant construction or reflective invocation rights.

Function invocation (provisional)

FunctionReflection provides Invoke(function: Object?, arguments: Object?[]) -> Result<Object?, ReflectionError> for native structural function values. It validates receiver, count and argument types before calling. Invalid input is a Result error; target faults propagate. See function invocation for supported signatures, null/no-result behavior and limits. Generic overloads are future work. This differs from .NET Delegate.DynamicInvoke's exception contract and uses the existing neoCLR reflection error convention.

Fields and type initializers

FieldInfo.IsInitOnly, IsLiteral and ConstantValue: Optional<Object> distinguish readonly storage from storage-free Int32 literals. GetFields applies Public/NonPublic and Instance/Static flags to all three categories; its default includes public instance and static fields. Metadata inspection and literal reads never initialize the owner. TypeInfo.IsBeforeFieldInit exposes relaxed initialization timing, while TypeInfo.TypeInitializer: Optional<ConstructorInfo> describes the private static .cctor. It is excluded from ordinary methods and public instance constructor enumeration. This descriptor does not grant direct invocation of a runtime-owned initializer.

Field GetValue/SetValue support public instance fields of nongeneric reference classes and public static fields of nongeneric nominal records. Static operations ignore the receiver, like .NET FieldInfo. Values remain exact boxed built-in scalars or compatible references/null. Readonly and literal writes return AccessDenied; wrong values return InvalidValue. Successful storage access runs normal type initialization, once per closed owner in the invocation; initializer faults remain terminal and are never converted to successful reflection results.

Interpreter execution and retained JIT/AOT access use ordinary verified field operations. Native compilation requires reflection-roots schema 7: each type row adds Boolean fields, fieldGetters, fieldSetters, and constructors to the schema-6 policies. Getters/setters require field metadata; constructor retention is descriptive and does not make private constructors callable. Existing generic reflection execution, custom boxed value payload and boxed instance-struct field limitations remain; these are execution gaps rather than erased type information. See docs/validation/field-reflection for the executable contract and fault checks.

These descriptor additions require a matching runtime and System.Runtime bundle; old RuntimeFieldInfo provider layouts must be rebuilt. Legacy source-origin token tables remain readable, with absent tokens reported as None. No change to ordinary Raven/.NET reflection or compiler Runtime Contract selection is implied.

Generic definition and construction (development)

TypeInfo.GetGenericTypeDefinition() -> TypeInfo returns the exact declaration of a generic definition or construction; nongeneric inputs fault. MakeGenericType(arguments: Sequence<TypeInfo>) -> Result<TypeInfo, GenericTypeError> closes a generic definition with ordered, closed arguments. It validates arity, argument admissibility and constraints. Errors are InvalidDefinition, ArgumentCount, InvalidArgument and NotRetained. Native execution can only return retained closed specializations; an absent transition returns NotRetained. Partially open types, Void, borrowed references, pointers and runtime handles are not supported arguments. Unlike .NET's exception-based API, recoverable construction errors use Result. No object is instantiated by either operation; constructor invocation still needs its own retention/access grant.

Constructing vector types

TypeInfo.MakeArrayType() -> TypeInfo returns the zero-based managed vector identity for its element type. It allocates no array storage. For example, typeof(int).MakeArrayType() equals typeof(int[]), and calling it on typeof(int[]) produces typeof(int[][]).

This follows the parameterless .NET Type.MakeArrayType contract. The rank-taking overload is not implemented. Open element types, void, byrefs, pointers and runtime handles are currently unsupported and fault; these are bounded implementation gaps, not a new general array contract. Native/JIT construction requires the resulting vector shape to be retained in the image, including through an executable array cast or an explicit type token. Type construction and reflective array creation share this inventory.

Useful consumers include ArrayReflection.Create(arrayType, values) and JsonSerializer.Deserialize(text, arrayType) when an element type is selected at runtime. Both have built-in tests. The JSON mapper already receives a complete target type and therefore does not reconstruct it unnecessarily. MakeGenericType has a production consumer in DI's open-registration closure: requested service arguments close the implementation definition before constructor planning and per-closed-type caching.