Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 879
Trey Mack Avatar asked Nov 01 '25 06:11

Trey Mack


1 Answers

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.

like image 99
Etienne de Martel Avatar answered Nov 02 '25 21:11

Etienne de Martel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!