You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Treat constructor arguments as required properties #78151
don't allow to compile above code because property doesn't have a setter - this makes sense because argument needs to be passed in the constructor anyway making required effectively redundant.
On the other hand when deserializing JSON Name does not have to be passed in the payload even though the only way to construct is through constructor - we will use default value (i.e. if value was int we'd pass 0 or null for string for you automatically):
varobj=System.Text.Json.JsonSerializer.Deserialize<Test>("{}");// no errorpublicsealedclassTest{publicstringName{get;}publicTest(stringname){Name=name;}}
Consider changing semantics here and make Name required instead making above code create error. Possibly there should be an option switch to opt-in to suggested behavior given this change will be breaking.
Example API suggestion (possibly consider enum and more generic name in case we need more related options in the future):
changed the title [-]Treat constructor arguments as required properties by default[/-][+]Treat constructor arguments as required properties[/+]on Nov 10, 2022
alternative design for that would be to provide Modifier for contract resolver but it's currently tricky to implement as a separate library because we don't have parametrized ctor APIs available yet (so basically user has to repeat JsonConstructor logic).
Extra overload of JsonConstructorAttribute sound good but for JsonRequired - we put [JsonConverter(...)] and [JsonNumberHandling(...)] directly on the property so I'm not sure why we'd do it differently for [JsonRequired]...
Activity
[-]Treat constructor arguments as required properties by default[/-][+]Treat constructor arguments as required properties[/+]krwq commentedon Nov 10, 2022
alternative design for that would be to provide Modifier for contract resolver but it's currently tricky to implement as a separate library because we don't have parametrized ctor APIs available yet (so basically user has to repeat JsonConstructor logic).
eiriktsarpalis commentedon Nov 10, 2022
Proposal looks good to me. We should also include provision for configuring requiredness on the type level:
and at the individual parameter level:
krwq commentedon Nov 10, 2022
Extra overload of
JsonConstructorAttributesound good but for JsonRequired - we put[JsonConverter(...)]and[JsonNumberHandling(...)]directly on the property so I'm not sure why we'd do it differently for[JsonRequired]...krwq commentedon Nov 23, 2022
marking as 8.0 because we should look at this in conjunction with other 8.0 items.