Overriding a method with a ref struct param in older C# versions

Viewed 180

I'm trying to override a JsonConverter<T> in the System.Text.Json package which has an abstract Read method which can be ovveridden as:

public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)

(Link to custom serialization here.)

Here ref Utf8JsonReader marks reader as a ref struct. "ref struct" is a feature introduced in 7.2. (which if you're not familiar is a struct that's meant to be used only on the stack. MSDN Link)

In my organization, one of our projects runs on an old compiler that can target only upto C# 6. Is there a way to write MSIL or code in C# 6 that can override the method signature and implement a derivative class of the above signature?

Otherwise you will see the following error: Struct 'System.Text.Json.Utf8JsonReader' is obsolete: Types with embedded references are not supported in this version

1 Answers

No, you cannot correctly implement a ref-struct based API using older versions of C# - the [Obsolete] is used very intentionally to prevent you from doing so (although in some other similar cases, a "mod-req" has been used to similar effect). ref struct has very specific demands, that could cause serious runtime problems if not satisfied (for example, an earlier compiler might attempt to box such a struct, which would be very very bad).

In short: update your C# version, or use an older version of the library which lacks this API which you cannot implement. As a third option, you could create your own library in a more recent version of C# that exists only to create an abstract implementation that overrides this API (perhaps with just throw new NotSupportedException();), and then inherit that from your down-level C# application. However, if the Utf8JsonReader API is now the primary (which I don't know, but could be the case), then this might cause the entire thing to be useless.

Related