Skip to content

Instantly share code, notes, and snippets.

@itn3000
Last active February 16, 2022 07:22
Show Gist options
  • Save itn3000/72b50256cebb4a8280bcf660c79cfda3 to your computer and use it in GitHub Desktop.
Save itn3000/72b50256cebb4a8280bcf660c79cfda3 to your computer and use it in GitHub Desktop.
Serialize error in System.Text.Json if ctor has "in" or "ref" keyword
// TargetFramework: net6.0
// this can be avoided if there is ctor with no "ref" or "in".
using System.Text.Json;
int z = 0;
var c1 = new C1(ref z);
try
{
JsonSerializer.Serialize(c1);
}
catch (Exception e)
{
Console.WriteLine($"c1 error: {e}");
}
class C1
{
// if public ctor with no ref and in, no exception.
// public C1(){}
public C1(ref int x)
{
}
}
c1 error: System.ArgumentException: The type 'System.Int32&' may not be used as a type argument.
at System.RuntimeType.ThrowIfTypeNeverValidGenericArgument(RuntimeType type)
at System.RuntimeType.SanityCheckGenericArguments(RuntimeType[] genericArguments, RuntimeType[] genericParameters)
at System.RuntimeType.MakeGenericType(Type[] instantiation)
at System.Text.Json.Serialization.Converters.ObjectConverterFactory.CreateConverter(Type typeToConvert, JsonSerializerOptions options)
at System.Text.Json.Serialization.JsonConverterFactory.GetConverterInternal(Type typeToConvert, JsonSerializerOptions options)
at System.Text.Json.JsonSerializerOptions.GetConverterInternal(Type typeToConvert)
at System.Text.Json.JsonSerializerOptions.DetermineConverter(Type parentClassType, Type runtimePropertyType, MemberInfo memberInfo)
at System.Text.Json.Serialization.Metadata.JsonTypeInfo.GetConverter(Type type, Type parentClassType, MemberInfo memberInfo, Type& runtimeType, JsonSerializerOptions options)
at System.Text.Json.JsonSerializerOptions.<InitializeForReflectionSerializer>g__CreateJsonTypeInfo|112_0(Type type, JsonSerializerOptions options)
at System.Text.Json.JsonSerializerOptions.GetClassFromContextOrCreate(Type type)
at System.Text.Json.JsonSerializerOptions.GetOrAddClass(Type type)
at System.Text.Json.JsonSerializer.GetTypeInfo(JsonSerializerOptions options, Type runtimeType)
at System.Text.Json.JsonSerializer.Serialize[TValue](TValue value, JsonSerializerOptions options)
at Program.<Main>$(String[] args) in D:\src\gitrepos\dotnet-sandbox\jsonnettest\Program.cs:line 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment