Required Syntax/ keyword.
I came across ‘required’ key word in C#. Not sure which version it was introduced. But now it exists, so just used copilot to enhance my understanding on the same.
public class Person
{
public required string Name { get; set; }
public int Age { get; set; }
}
If you are a C# developer, u might haven’t skipped properties. Now adding required before the variable makes it like you have to set the value explicitly. If it’s not a required property, C# takes care of the setting default values.
var p = new Person(); // ❌ Error: Name is required
var p = new Person { Name = “Ram” , Age = 36 }; // This is correct.
This applies to fields and properties. This is different from [required] attribute.
While understanding about this, I had a doubt you can set the properties by adding parameters to the constructors. Let say,
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Person(string name)
{
Name = name;
}
What difference it could bring? I checked with copilot again. I could understand that,
Constructors are enforced during the compile time and required are forced only during run time.
By this type, you can evolve the code, but in case constructors we have to make sure fix during the compile time. Also, the code looks clean and neat in terms the required.
Refactoring is flexible — If I have to introduce a new parameter in the constructor, I have to makes changes all the way where all the initialization has happened but not the case with required.
Fields can grow! agreed!
But usually, developers introduce parameter constructor for the sake the sake of validation even before creation object which in case of ‘required’ is not possible.
So, in the end I am good at ‘required’ 😛