-
Notifications
You must be signed in to change notification settings - Fork 4.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Treat constructor arguments as required properties #78151
Comments
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis Issue DetailsCompiler private class Test
{
public required string Name { get; } // error
public Test(string name)
{
Name = name;
}
} 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 On the other hand when deserializing JSON var obj = System.Text.Json.JsonSerializer.Deserialize<Test>("{}"); // no error
public sealed class Test
{
public string Name { get; }
public Test(string name)
{
Name = name;
}
} Consider changing semantics here and make Example API suggestion (possibly consider enum and more generic name in case we need more related options in the future): public partial class JsonSerializerOptions
{
public RequireConstructorParameters { get; set; }
} Related: #78098
|
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). |
Proposal looks good to me. We should also include provision for configuring requiredness on the type level: public sealed class Test
{
[JsonConstructor(RequireParameters = true)]
public Test(int p1, int p2, int p3, int p4, ...)
{
}
} and at the individual parameter level: public sealed class Test
{
public Test(int p1, [JsonRequired] int p2, int p3, int p4, ...)
{
}
} |
Extra overload of |
marking as 8.0 because we should look at this in conjunction with other 8.0 items. |
Compiler
required
keyword semanticsdon'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 wasint
we'd pass 0 ornull
forstring
for you automatically):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):
Related: #78098
The text was updated successfully, but these errors were encountered: