MissingMethodException when setting init-only property from another assembly in netstandard2.1 lib running on .NET 6

1 day ago 2
ARTICLE AD BOX

From what I can see this version of RestSharp's package comes with builds for (.NET Standard 2.0, .NET 5 and .NET 6)

The .NET Standard 2.0 assembly which LibA compiles against also declares a polyfill for IsExternalInit which the compiler prefers over the one you defined.

We can demo this by extending the repro a little bit:

namespace ClassLibrary1 { public class Repro { public static void Run() { var r = new RestRequest("") { ResponseWriter = null }; var r2 = new Repro() { ResponseWriter = null }; } Func<Stream, Stream?>? _responseWriter; public Func<Stream, Stream?>? ResponseWriter { get => _responseWriter; init { _responseWriter = value; } } } } namespace System.Runtime.CompilerServices { internal static class IsExternalInit { } }

The IL (from ILSpy) where you can see that different polyfills are used for the two init setter calls:

callvirt instance void modreq([RestSharp]System.Runtime.CompilerServices.IsExternalInit) [RestSharp]RestSharp.RestRequest::set_ResponseWriter(class [netstandard]System.Func`2<class [netstandard]System.IO.Stream, class [netstandard]System.IO.Stream>) /* 0A00000F */ callvirt instance void modreq(System.Runtime.CompilerServices.IsExternalInit) ClassLibrary1.Repro::set_ResponseWriter(class [netstandard]System.Func`2<class [netstandard]System.IO.Stream, class [netstandard]System.IO.Stream>)

(Also see the well-written answers under this question for more info about modreq modifier, init properties).

When you run the .NET 6 host, the .NET 6 assembly of RestSharp is loaded (and not the .NET 2.0 Standard which we have compiled against). So the annotation of the init property is not using the polyfill but the built-in IsExternalInit type.

So my bet is the type mismatch leads to binary incompatibility (RestSharp polyfill vs real thing)

This can be somewhat verified if you run a .net-core 3.1 host that loads the .NET Standard 2.0 RestSharp assembly. From my tests there is no runtime exception there.

As solutions, probably multi-targetting of LibA for .NET 5 / .NET 6.

Read Entire Article