Swashbuckle.AspNetCore icon indicating copy to clipboard operation
Swashbuckle.AspNetCore copied to clipboard

[Question]: Default values of List/Dictionary fields

Open retroandchill opened this issue 3 weeks ago • 1 comments

What are you wanting to achieve?

I'm having trouble setting the default values for collection fields. Since the creation of a reference type isn't a compile-time expression I can't use DefaultValue like I can with primitives and enums. Is there any way to property set the default value of a collection type? I don't like the default value of collections being null, I thing they should always be initialized to an empty collection, and I want the generated spec to reflect that.

What code or approach do you have so far?

So far I've tried a few things, and neither of them work.

    [JsonPropertyName("SupportedTargetPlatforms")]
    [DefaultValue(new List<string>())] // Doesn't compile
    public List<string> SupportedTargetPlatforms { get; set; } = [];

    [JsonPropertyName("SupportedTargetPlatforms")]
    [DefaultValue("[]")] // Shows up as the default in the spec, but the property still shows as being nullable despite that
    public List<string> SupportedTargetPlatforms { get; set; } = [];

Additional context

No response

retroandchill avatar Feb 01 '25 02:02 retroandchill