Trimming and Reflection in .NET. What Do IL2026 and IL3050 Promise?

Trace a missing XML name and an empty HTTP error to the published files. Compare analyzer warnings, generated JSON metadata and the native method map before signing off.

Under a work lamp, a Victorian instrument maker inspects the empty fitted recess where a required brass part belongs.

How .NET Runs Your Code, part 6 of 11. Previous, Native AOT Has No JIT: What Does Expression.Compile Run? Next, Build Host, Target, Receiver: Where a Native .NET Build Runs.

Intake’s partner reads the name of a job from /job/name in an XML document. In part 1 the ordinary exporter wrote the name and the native exporter crashed. Both build logs warned about the same serializer. Now Lena, who maintains the exporter, keeps the just-in-time compiler (JIT) and asks the publisher to remove unused code. Will the exporter write the name, throw the familiar exception, or do something else?

Dana, the release owner on this fictional team, has another failing client. A blank job name should produce a JSON error explaining what to correct. One published service gives the client an empty server error even though it accepts a valid job. Lena can investigate both failures by following a value from application code through its serializer to the client. At which step did the name or the explanation disappear?

  • A trimmed exporter with its JIT still present can exit zero and write a job element with no name. Compare the parsed document with the input.
  • A native build can serialize the original type through reflection when its required members survive. Preserving that type covers only the tested schema.
  • A missing generated JSON description can turn an otherwise valid client error into an empty 500. Naming the generated property in the handler makes the same omission fail at compilation.
  • Assign each feature an input and a consumer check. A successful publish, a warning count or a status code alone leaves a gap.

A direct call and a reflective lookup give the publisher different information

Start with what the partner will parse. For input R&D <night>, the document must have a job root and exactly one name child. Its decoded value must equal that original string, including the punctuation. Repeat with rebuild-index, Desk lamp and the empty string. Even an empty name requires the child element. A well-formed XML document can still violate the partner’s schema.

Read the assignment new PartnerJob { Name = name } in the exporter. It constructs an object and calls the setter for Name. To send the value back out, XmlSerializer needs to discover a readable property and its XML annotations. It also inspects constructors while importing the type. This inspection at run time is reflection. The source assignment and the serializer have different reasons to need a member of the same type.

Trimming follows references from the program’s entry points and from any types or members explicitly marked to be kept, called roots. A direct call gives the analysis a reference to follow. A library searching a type by convention can need a member that no call names. Metadata describes those members to the running program. An ordinary trimmed build still has its JIT. Native AOT compiles machine code ahead of time. Which observation would distinguish missing metadata from missing code generation?

Two warning codes describe different promises

At the marked constructor in the shared exporter, read both warnings. Which concerns members that could disappear from the file, and which concerns code that the process might need to generate later?

Rider shows both IL2026 and IL3050 on the XML serializer constructor.
Rider · macOS Rider flags two promises at the same call. One concerns metadata and the other the ability to generate code.

The constructor and the subsequent Serialize call each carry two warnings. The excerpt below keeps the source locations and codes from the ordinary analysis. In the full native publish log the same operations also appear during native compilation. Count the source calls separately from the times a build tool reports them.

PartnerExport.cs(16,26): warning IL2026
PartnerExport.cs(16,26): warning IL3050
PartnerExport.cs(17,9): warning IL2026
PartnerExport.cs(17,9): warning IL3050

IL2026 means the caller reaches an API marked RequiresUnreferencedCode. The called implementation might need members the trimmer cannot prove necessary. IL3050 concerns RequiresDynamicCode. Some uses of that API can require machine code generated after the program starts. An analyzer issues these warnings where it cannot guarantee safety for all allowed inputs. It does not run this export with Lena’s one type. Microsoft’s IL2026 guidance and IL3050 guidance.

The ordinary build warns because its project asks for analysis

In the ordinary build there is a JIT, and the untrimmed application assembly includes the public members in question. Why does that build report a problem at all? Look at the property in Intake.Export.csproj. The shared project advertises its intent to support Native AOT and enables the corresponding analyzers.

<IsAotCompatible>true</IsAotCompatible>

On both tested SDK lines the ordinary build reported four distinct source diagnostics with that property on, and zero with it off. Both ordinary exporters wrote the right document for the four inputs. A native publish with the ordinary project’s opt-in disabled still reported the risk and the serializer still failed. Suppressing the two codes removed the messages and left all four failed exports unchanged. That leaves a question the log cannot answer. What did the executable actually send?

The Error List locates IL2026 and IL3050 on the two XML serializer calls in PartnerExport.cs.
Visual Studio Insiders · Windows The Release build succeeds. Visual Studio reports IL2026 and IL3050 at both new XmlSerializer(...) and Serialize(...).

The JIT can survive trimming while the job name disappears

Give the original, native and trimmed programs the same input. Look for the decoded value and for the exit independently. A byte count alone cannot tell you that the name child exists. The terminal experiment starts the three published executables and gives their stdout bytes directly to an XML parser.

.NET · Apple Silicon Read back /job/name in each document. The trimmed executable exits cleanly after writing only the root element. Full recording

Suppose Dana’s pipeline flags any change in the partner file’s length. Below are the .NET 11 exports for rebuild-index. Every process in the table exited zero. The first break is the actual UTF-8 byte sequence between the XML declaration and <job. Which outputs can the partner accept?

ExporterReceiverFirst break (hex)Total bytesParsed /job/name
Untrimmed JITmacOS Arm64, Linux x640A (LF)179rebuild-index
Untrimmed JITWindows x640D 0A (CRLF)182rebuild-index
Trimmed JITmacOS Arm64, Linux x640A (LF)145Child absent
Trimmed JITWindows x640D 0A (CRLF)146Child absent

Accept the untrimmed export on all three receivers. macOS and Linux use a line feed at each of the three breaks. Windows adds a carriage return before each line feed, and the parser still recovers the same name. Hold the trimmed exporter on all three. Each trimmed document has a job element with no name child. If a customer checks an archived Linux file byte for byte, even the ordinary Windows export differs at the first line ending. Part 11 applies that stricter check to two writers on one receiver.

The original native exporter produced no document at all. The trimmed JIT exporter wrote a well-formed document with the wrong content. Where did each exporter lose the name?

Open the native exception chain and read one level past the familiar outer message. Below are the exception messages and the first frame of the inner failure. The remaining stack frames are omitted. Later in that stack the serializer enters SerializeUsingReflection.

Unhandled exception. System.InvalidOperationException: There was an error generating the XML document.
 ---> System.InvalidOperationException: Intake.Export.PartnerJob cannot be serialized because it does not have a parameterless constructor.
   at System.Xml.Serialization.TypeDesc.CheckSupported()

Lena did not delete the C# constructor. The native file contains a type entry for PartnerJob. Can the serializer use the public members it expects to find there? Inspect the Native AOT compiler’s map, a list of named items it placed in the image. The download includes the full compressed XML maps in results/mac/part06. Filter for PartnerJob and compare the MethodCode rows before and after a descriptor tells the compiler to preserve the type.

Mac Arm64 native publish, .NET 11Type entrySeparate constructor, getter and setter code rowsFour names recovered
OriginalPresentNone under the type’s name0 of 4
Preserve PartnerJobPresentConstructor 28 B, getter 20 B, setter 28 B4 of 4

The map counts emitted code for separately named methods. A direct new PartnerJob can be inlined, so the missing constructor row alone cannot establish whether an object was constructed. The exception identifies the failed reflective lookup. In the second native row, preserving the type restores the partner’s document while the process still cannot generate new code. Which member does the ordinary trimmed exporter lose?

Data flow

The export can construct a job whose public constructor the serializer cannot find

Export commandPartnerExport.WriteXmlSerializerreads a type descriptionPartnerJobnamed in the fileConstructorneeded by the importerName accessorneeded by the XML writer
  1. The command supplies a name to the shared export method. The partner expects that value inside one named element.
  2. Direct calls give the compiler a path from the entry point into the serializer and the application code.
  3. XmlSerializer also inspects the type for members by convention. The unrooted native map names the type itself.
  4. No separate constructor body appears under that type’s name. The native serializer reports that it cannot find a parameterless constructor.
  5. In the trimmed JIT assembly the setter remains and the getter disappears. The serializer emits an empty job.
  6. A descriptor preserves this type. Constructor, getter and setter bodies appear in the native map and the partner reads the name.

Mac Arm64. The native method maps, original and rooted XML results, and trimmed-assembly inspection are under results/mac/part06.

The trimmed JIT assembly still contains the setter and constructor. Its intermediate language has no getter for Name. Intake can assign a value, but the serializer has no readable property from which to recover it. Turning off dynamic code with -p:DynamicCodeSupport=false also produced a nameless job. Lena checked the written runtime configuration and the process flags because the SDK had overwritten a raw runtime option in an earlier control.

Two explicit XML elements give the known partner a testable promise

Lena controls this writer and knows every element the partner requires. She can write the name as element content and let the XML library escape it. If the caller types R&D <night>, what should the partner’s parser recover?

using var writer = XmlWriter.Create(destination, new XmlWriterSettings { OmitXmlDeclaration = true });
writer.WriteStartElement("job");
writer.WriteElementString("name", name);
writer.WriteEndElement();

This branch of PartnerExport.Write has no convention-based member discovery. It produced the original parsed names and no IL warnings in the bounded writer publishes. Its promise ends at this two-element schema. If a customer must supply an unknown type after release, this implementation has no code that maps that type to XML. An open-ended plugin requirement would call for a different deployment or an explicitly extensible interchange format.

What about generating the serializer at build time? The Microsoft XML Serializer Generator produced ExportJob.XmlSerializers.dll in both tested publish folders. On the ordinary build the program recorded loading that assembly and recovered all four names. The native build still failed all four exports and reported no corresponding assembly-load event. A generated file alongside the executable did not make this Native AOT program use it. Compare that experiment with the JSON generator below, whose property the application references directly at compile time. Microsoft XML Serializer Generator.

Validation can succeed even when writing the error fails

There is a second consumer. A client sends {"name":""} to POST /jobs and needs to know which field to correct. The service should return HTTP 400 with a machine-readable code and message. The handler validates the name before it puts anything in the journal. It also has to serialize the error value, a different .NET type from the successful acknowledgement.

Intake uses a generated JSON context, a build-time description of how to read and write explicitly listed types. It includes the request, the queued-job acknowledgement and the journal response. In the failing variant it omits JobProblem, the typed error. The resolver is the component the writer asks for a type’s description. A lookup by typeof(JobProblem) can compile even when that description is missing. Where does the 500 come from if validation worked? How System.Text.Json uses a generated context.

Sequence

Validation rejects the job before writing the error fails

  1. An empty name gives the handler a valid reason to reject this request immediately.
  2. The invalid branch creates an error value before the journal can record a job. A subsequent GET checks that decision.
  3. The response writer now needs a description of JobProblem. Handling the request and describing its response are separate operations.
  4. With the generated registration missing and reflection disabled, the resolver throws a NotSupportedException while writing the response.
  5. Kestrel logs the unhandled exception and sends an empty error response. The job has still not been accepted.
  6. Add the missing generated description. The same invalid request receives the intended status and its corrective message.

Eight HTTP requests per published configuration on Mac Arm64. Compare the native and registered API logs with the response bodies in results/mac/part06.

The clip sends a blank name and then a valid one to each fresh published server. Watch which server acknowledges the valid job despite failing to explain the rejection. The eight-request check in the download also reads the journal before and after the invalid submissions.

ASP.NET Core · Mac Arm64 Read down the invalid-request column while keeping the valid POST as a positive control. Registering JobProblem restores the typed error. Full recording

Read the first exception line from the failed native request. Kestrel, the web server, logged event 13 for an unhandled application exception. The line identifies the type the writer needed and the resolver it asked.

The filtered server log reports JobProblem in the exception following Kestrel event 13.
Kestrel · ASP.NET Core Kestrel event 13 identifies the request failure. The following exception names the missing JobProblem serialization metadata.

The invalid request appended no job. A subsequent valid request returned 202 and the exact acknowledgement. Repeating the invalid request left the one accepted job untouched. The native publish with the missing type reported no coded warning for this lookup. Delegating lookup to the framework through TypedResults.BadRequest produced the same native 500. In that control the ordinary publish reported six warnings at route registration sites, while the native publish had no corresponding IL warning. Both pieces of information matter when deciding whether the negative path needs a test.

The ordinary control can reproduce the native error

Keep the blank name fixed. The client should receive HTTP 400 with code and message. Start with the working ordinary runtime and switch off its reflection fallback. Will it still write those fields? Then use the failing native build as the starting point for two repairs, enabling reflection or registering the error type. Predict which one satisfies the client.

Explorable

A 400 can still leave the client without either error field

Ordinary JIT Blank-name responseHTTP 400code + message60 B in body Generated entry for JobProblemMissing JSON reflection fallbackEnabled Journal after rejection: still empty
  1. The client gets both fields even though the generated context lacks JobProblem. Predict what happens if this very same JIT runtime loses its reflection fallback.
  2. The service still rejects the job. Without either source of metadata, writing its explanation fails and the client receives an empty server error.
  3. The native build reaches the same failure. Keep this candidate as the reference when comparing the next two attempts to restore the error body.
  4. Relative to the previous case, enable reflection alone. The status becomes 400. The two bytes form an empty object, so the client still cannot explain the rejection.
  5. Return to the native candidate with reflection off. Register JobProblem in the generated context and the client can read both fields again.

Mac Arm64. Blank-name responses and subsequent journal reads come from the JIT, reflection-disabled, native, reflection-enabled and registered API cases in results/mac/part06.

The ordinary process can reproduce the failure with its JIT intact. The native process can recover with its JIT still absent. What changed in each pair was the resolver’s ability to describe this particular response.

The tempting shortcut was to turn reflection back on. Its {} parses as JSON, just as the nameless job parses as XML. Have the client read name-required from code and A job name is required. from message. The empty object fails both assertions even though its HTTP status is correct. How can Lena make a missing description visible before this request reaches a receiver? Preserving client behavior while changing a module.

Name the generated property to make the omission a compiler error

Open the generated JobJson.JobProblem property in the correctly configured project. It returns a JsonTypeInfo<JobProblem>, a description the serializer can use for this particular response type. The generator also emits the property descriptions used to encode the error. The generated file for the registered case is in the download, so you can inspect it without installing the IDE.

The generated context in Rider exposes the registered JobProblem property and getter.
Rider · macOS Registering JobProblem gives JobJson a named JsonTypeInfo property for the error response.

Look up the error type while responding

var type = (JsonTypeInfo<JobProblem>)serializer.GetTypeInfo(typeof(JobProblem));
await TypedResults.Json(problem, type, statusCode: 400).ExecuteAsync(http);

The handler compiles with the type missing from the generated list. Only a request that needs this response forces the lookup.

Ask directly for the generated error property

[JsonSerializable(typeof(JobProblem))]
// In the handler:
await TypedResults.Json(problem, JobJson.Default.JobProblem, statusCode: 400).ExecuteAsync(http);

The class must expose the property named in the handler. Removing the declaration makes the compiler point to the exact response that needs it.

The test obtains type information from JobJson.Default itself. Its list of three public responses comes from the API promise. Removing the registration makes the JobProblem case fail while the two success types still pass. Enumerating the generated list to build the test would quietly drop the very case Lena needs to detect.

Rider · macOS The queue and list rows already passed. Restoring the error type changes the one failing row in the same test. Full recording

Now take the strict version of the handler and omit the registration. Both the ordinary and the native command stop at CS1061. Each says that JobJson has no definition for JobProblem. The error identifies a mismatch between the source contract and generated code before a customer can submit a job. How do the declarations, the handler and the independent test each contribute?

Code walkthrough

Naming the generated property moves an omission into the build

[JsonSerializable(typeof(SubmitJob))]
[JsonSerializable(typeof(QueuedJob))]
[JsonSerializable(typeof(JobQueue))]
#if REGISTER_JOB_PROBLEM
[JsonSerializable(typeof(JobProblem))]
#endif
public partial class JobJson : JsonSerializerContext;

await TypedResults.Json(problem, JobJson.Default.JobProblem, statusCode: 400).ExecuteAsync(http);

[Theory]
[InlineData(typeof(QueuedJob))]
[InlineData(typeof(JobQueue))]
[InlineData(typeof(JobProblem))]
public void EveryPublicResponseHasGeneratedMetadata(Type type)
{
    var info = JobJson.Default.GetTypeInfo(type);
    Assert.True(info is not null, $"The generated response context does not contain {type.Name}.");
    Assert.Equal(type, info.Type);
}
  1. The declarations name request and success types that the JSON generator must describe while building the program.
  2. The handler passes the generated JobProblem description explicitly when it writes the bad-request response.
  3. Remove the registration and the property the handler names no longer exists. CS1061 stops both builds before deployment.
  4. Restoring the declaration gives the generator a type to describe and the handler an actual property to reference.
  5. The test independently lists every documented JSON response type and asks the generated context to return its metadata.

Excerpts from JobJson.cs, the promise API’s handler and its response-contract tests. The named-property publish logs are in results/mac/part06.

Rider marks JobJson.Default.JobProblem in the named handler and shows CS1061 at Program.cs line 31 in the measured build log.
Rider · macOS With a named response property, the compiler points at the handler as soon as the registration is removed.

There is another option for shortening the feedback loop. In an ordinary development project with the registration omitted, dotnet run returned 400 and the full explanation. Setting PublishAot in the project for the development run changed the observed dynamic-code and JSON reflection flags to false. The same invalid request then returned the empty 500. This helps a team targeting Native AOT discover an omission during development. A library consumed in several modes still needs a matrix, since changing the everyday project settings changes which fallback developers see.

Preserve a closed set when the serializer belongs to somebody else

Suppose the partner requires a serializer that Lena cannot replace. She can tell the trimmer to keep a known type and its members. In the descriptor below, check both the assembly and the type name. Would another class with the same XML attributes qualify?

<linker>
  <assembly fullname="Intake.Export">
    <type fullname="Intake.Export.PartnerJob" preserve="all" />
  </assembly>
</linker>

Try that prediction on the executable built with KeepPartner=true and SecondPartner=true. Its export and second commands use the same serializer in the same native binary. Both types declare job and name. Only PartnerJob appears in the descriptor. Open net11-intake-second.json in results/mac/part06. The four cases round-tripped through PartnerJob. All four entries under second_type failed through SecondJob. The descriptor follows a .NET type name, regardless of how similar the two XML schemas look.

Wider declarations carry their own cost. Keeping the entire application assembly also restored the original control exporter. Keeping that assembly plus the XML library and the core library together produced an Apple linker error about missing symbols in this experiment. An annotation requesting all dynamically accessed members directly on the original job type did not rescue its native serializer either. Those are observed outcomes of these configurations. They are poor substitutes for specifying which information flows through a helper’s parameter.

A helper can tell the trimmer exactly what its caller must supply

Consider a library helper that returns the public property names of a supplied type. The helper has a Type parameter and calls GetProperties for public instance properties. Reading its source, you know what it will require. Give the tool the same information where the value enters the helper.

static string[] WireProperties(
    [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)]
    Type contract)
{
    return contract.GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .Select(property => property.Name).ToArray();
}

In the unannotated trimmed program this helper produced IL2070 and printed no property name. With the requirement on the parameter, the call WireProperties(typeof(PartnerJob)) gave the analysis a known type at its call site. The trimmed program printed Name and the warning disappeared. The parameter expresses what the next operation needs. It does not tell an arbitrary XML serializer how to describe every type it might encounter. Preparing libraries for trimming.

When a public operation really does require unbounded reflection or runtime code generation, annotating the public API lets its caller see the requirement. Maintain the promise per feature. Npgsql’s 8.0 release notes distinguish Native AOT and trimming support from features that require explicit opt-ins for dynamic type mapping. A package version tells a team where to look. The operation, inputs and publish mode tell it what to exercise. Npgsql 8.0 release notes.

Two runtime lines agree on the checked failures

Would upgrading the SDK remove either warning from Lena’s serializer? Count distinct diagnostics from an ordinary Intake.Export build, then compare the two phases in the native publish log. Each row uses the same call sites on the Apple Silicon Mac.

SDKOrdinary analysis off / onNative source diagnosticsNative compiler diagnostics
10.0.4040 / 444
11.0.1000 / 444

The upgrade changed none of these counts. Look at the tasks in the native binary log to separate the repeats. The C# compiler, under CoreCompile, sees source annotations. The native compiler invoked by IlcCompile examines the application being prepared for this receiver.

The Exec task inside IlcCompile lists the four native compiler diagnostics for Intake.Export.
MSBuild Structured Log Viewer · Windows Expand Exec inside IlcCompile. Both the serializer construction and its call produce a warning about trimming and a warning about dynamic code.

On both runtime lines the Mac Arm64, Windows x64 and native Linux x64 runs agreed on all three outcomes. The explicit writer preserved the name, the unrooted native serializer failed, and the trimmed JIT serializer omitted the child. Python recorded the native failure as -6 on macOS and Linux and 3221226505 on Windows. The empty output and missing-constructor diagnostic identify the same failed operation across platforms.

On Windows the corrected CLI explicitly writes UTF-8. Part 1 showed how a legacy console encoding could independently spoil an otherwise correct export. Rechecking the output bytes keeps that transport error separate from the missing member. The worker uses the same exporter. Its settings come from a concrete WorkerSettings object initialized from command-line arguments, so this sample supplies no portability claim about a reflective options binder. The operations console remains an MVC application on the JIT.

Decide whether to ship each feature before assigning work to remove a warning. In this table a passing export means the partner parsed the right name. A passing rejection means the client read the specified error and the journal stayed unchanged. Which column should contain an empty JSON object returned with HTTP 400? Judge the body before using the warning log to choose a row.

Relevant warningConsumer check passesConsumer check fails
PresentThe untrimmed serializer passed. Qualify that schema on that build and keep the warning open for other modes.The native serializer cannot import its type. Use an explicit writer for a fixed document you own, or preserve a named partner type if you must keep the serializer. Rerun the partner’s parser.
AbsentThe bounded writer passed. Keep its name-round-trip test as a requirement for the next schema revision.The missing JSON type broke the rejection. Request its generated property and test the response with fallback disabled. Check the status, both fields and the journal.

Dana records that the explicit writer on this native target returned the required XML for four names. A new payload type reopens the decision. Try that reasoning on a proposed oversized-job error. Does supporting it require another generated type? If it reuses JobProblem, exercise the new branch and assert its own error code, message and journal state. If it introduces a different response type, first add that type to the independent resolver test. Run the published API with fallback off before accepting the repair.

Run an export and a rejected request on the published files

From the root of the download, use Python 3.10 or newer, the pinned .NET SDK and the native compiler for your host. The first command publishes the exporter and API candidates, feeds the XML bytes to a parser, sends real requests to temporary loopback servers, and writes the results in a new folder. The second checks the generated descriptions without starting a server. Read the returned name or the error body before comparing warning counts.

python3 tools/part06.py --study demo --line 11 --out my-promises
dotnet test src/Part06.Promise.Tests -c Release

For the warning, map and descriptor controls, read the guide beside Part06.Promise. Lesson 03 and the companion clinic follow the original exporter and error response on screen. The downloadable matrix here lets you change the target, inspect the method map, add an unlisted type and test both SDK lines against the same reader. How event formats affect schema compatibility.

  • Give every compatibility warning an owner, a feature and a tested configuration.
  • Test the bytes with the partner’s parser, including punctuation, spaces, and the empty value.
  • Send an invalid request before and after a valid one. Assert the error body, the status and the journal’s contents.
  • Use a generated property or enumerate required types in an independent resolver test.
  • Record what a descriptor preserves and add a test for the next type before extending the promise.

Further reading

Intake’s memo lists the XML partner export and the API error response as separate promises. The explicit writer and registered error type passed their consumer checks. The old native serializer, missing error type and unlisted partner schema have reproducible reasons to hold.

These files ran on specific machines. A working Mac binary tells Ravi what the Mac did. The service will run in Linux containers and operators also need a Windows tool. Which machine can build each file, and which receiver has actually run it?

How .NET Runs Your Code, part 6 of 11. Previous, Native AOT Has No JIT: What Does Expression.Compile Run? Next, Build Host, Target, Receiver: Where a Native .NET Build Runs.

Written by

Marcin Borecki

Software architect and entrepreneur, Microsoft Regional Director since 2014, with CloudExpert since 2011. I help teams design, measure and ship .NET, Azure, data and AI systems that hold up in production.

Facing this problem in your own system?

I run focused investigations and architecture reviews, and take hands-on roles as an accountable chief architect.

See how I can help