[Proposal] add a required keywork for properties and perhaps member #8958
-
In C#, object properties can be initialized using the with keyword or object initializers ({} syntax). For example: public class A
{
public string Sample { get; set; }
public string Sample2 { get; set; }
}
var a = new A
{
Sample = "test"
}; When properties are mandatory, the preferred approach is to initialize them via a constructor. However, this becomes unwieldy when a class contains many required properties. For instance, a constructor with 10 or more parameters can be difficult to read, maintain, and use effectively. Proposal In the constructor. public class A
{
public mandatory string Sample { get; set; }
public string Sample2 { get; set; }
}
// Valid: All manadatories properties initialized.
var a = new A { Sample = "test" };
// Error: `Sample` is required but not initialized.
var b = new A();
// Valid: `Sample` initialized via constructor.
var c = new A("test"); Benefits Problem var a = (A) Activator.Create(typeof(A))
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
See: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/required |
Beta Was this translation helpful? Give feedback.
See: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/required
SharpLab