I have the following code:
public abstract class Base
{
}
public class Foo : Base
{
}
public class Bar : Base
{
}
public static void TestA()
{
JsonPolymorphismOptions options = new JsonPolymorphismOptions
{
DerivedTypes =
{
new JsonDerivedType(typeof(Foo), nameof(Foo)),
new JsonDerivedType(typeof(Bar), nameof(Bar)),
}
};
}
It compiles just fine.
However, the following code does not compile:
public static void TestB()
{
IList<JsonDerivedType> subtypes = new List<JsonDerivedType>()
{
new JsonDerivedType(typeof(Foo), nameof(Foo)),
new JsonDerivedType(typeof(Bar), nameof(Bar)),
};
JsonPolymorphismOptions options = new JsonPolymorphismOptions
{
DerivedTypes = subtypes
};
}
I get a
Error CS0200 Property or indexer 'JsonPolymorphismOptions.DerivedTypes' cannot be assigned to -- it is read only
Well, I can obviously assign it in the first initializer in TestA
, why not in TestB
? And is there a way to assign a previously assembled list to the DerivedTypes
property in TestB
without hard-coding it?
I assume the problem is not related to System.Text.Json.Serialization.Metadata.JsonPolymorphismOptions
but rather to my general usage of initializer syntax.