Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Which C# language feature allows initializing a property that only provides a get implementation?

I’m working with the System.Text.Json serializer, and need to provide custom serialization logic for one property of my overall object. That’s not the issue, it’s working, but I don’t understand how. This is the sample provided in the MS docs.

https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/converters-how-to?pivots=dotnet-6-0#registration-sample—converters-collection

var serializeOptions = new JsonSerializerOptions
{
    WriteIndented = true,
    Converters =
    {
        new DateTimeOffsetJsonConverter()
    }
};

jsonString = JsonSerializer.Serialize(weatherForecast, serializeOptions);

Best I can tell, the Converters property only implements a getter.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Hover description in VSCode

Here’s the decompiled code I get with a Go To Definition.

        // Summary:
        //     Gets the list of user-defined converters that were registered.
        //
        // Returns:
        //     The list of custom converters.
        public IList<Serialization.JsonConverter> Converters { get; }

And, what I think is the original code.

https://github.com/dotnet/runtime/blob/main/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Converters.cs#L23

What magick explains this?

>Solution :

It’s a collection initializer.

Converters is a collection. In the following code:

Converters =
{
    new DateTimeOffsetJsonConverter()
}

You’re not assigning to Converters itself. Since the type of Converters is a type that implements IEnumerable and has an Add method with the appropriate signature, the compiler simply generates code that calls that Add method and passes it your DateTimeOffsetJsonConverter instance. The Converters property itself does not need a setter because you only need the collection itself.

The fact that it looks like assignment is just a quirk of the grammar.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading