[Proposal] Have a way to enforce field or property initialization on the constructor #8142
Unanswered
opcodewriter
asked this question in
Language Ideas
Replies: 2 comments 13 replies
-
You can use SetRequiredPropertiesAttribute to specify that the constructor satisfies the required properties of the class: class Person
{
public required int Id { get; init; }
[SetsRequiredProperties]
public Person(int id) { Id = id; };
}
var person = new Person(1); The attribute is an all-or-nothing switch, meaning that a constructor adorned with it will be expected to have set all of the required properties. |
Beta Was this translation helpful? Give feedback.
3 replies
-
Related: #8137 |
Beta Was this translation helpful? Give feedback.
10 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
C# does not have a way to enforce having a property initialized on the constructor.
The closest thing is using the required keyword, but it works only if you use object initializer.
The following code will give a compilation error:
Setting the [SetRequiredPropertiers] does not help, it basically tells the compiler to believe all the required properties are set.
I don't want to trick the compiler in any way, that defeats the whole purpose why I need this feature.
I'm looking for a solution where the compilers actually checks if the required fields or properties are actually set, like how required works for the object initializers.
Such a feature be very handy, it really ensures the required fields / properties are set even when using a constructor.
I am NOT asking for the required keyword to be modified, such a change won't be possible as it would break people's code.
I don't care if a new feature/keyword would be introduced.
Beta Was this translation helpful? Give feedback.
All reactions