[API Proposal]: System.Text.Json new setting TreatNullableConstructorParametersAsOptional
- Dominant language
- C#
- Stars
- 18.3k
- Forks
- 5.6k
- PR merge metrics
- PR metrics pending
Description
### Background and motivation
My team stumbled on the similar issue which is described here [106392](https://github.com/dotnet/runtime/issues/106392), discussion under this issue is pretty lengthy so I won't be repeating every detail. What we want to achieve basically is to use nullability in our API contracts to express both the fact that certain parameter accepts null as a valid value and that it is optional (client should be able to omit it in his JSON request). Opposite is also true if the parameter is not marked as nullable, null value is not valid and it is required (can't be omitted in JSON request). By nullable parameters I mean both value types wrapped in `Nullable` and reference types annotated with `?`.
It means that deserializing below class from empty JSON (`{}`) should succeed.
```csharp
public class User
{
public string? Name { get; }
public User(string? name)
{
Name = name;
}
}
```
and below should fail
```csharp
public class User
{
public string Name { get; }
public User(string name)
{
Name = name;
}
}
```
Based on what we can read [here](https://github.com/dotnet/runtime/issues/106392#issuecomment-2288863358) I understand that you don't want to fix the bug in `RespectNullableAnnotations` setting due to breaking change, even though this behavior may be misleading to many (to how many it is hard to know because this issue was closed so it can't be upvoted). In that context is it possible to add new setting `TreatNullableConstructorParametersAsOptional` which we would be able to use in combination with existing settings (`RespectNullableAnnotations` and `RespectRequiredConstructorParameters`) to achieve desired behavior?
### API Proposal
```csharp
new JsonSerializerOptions
{
RespectNullableAnnotations = true,
RespectRequiredConstructorParameters = true,
TreatNullableConstructorParametersAsOptional = true //new setting
}
```
### Alternative Designs
_No response_
### Risks
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.