How to make a property required in C#?
c#
Solution
If you mean "the user must specify a value", then force it via the constructor:
public YourType(string documentType) {
DocumentType = documentType; // TODO validation; can it be null? blank?
}
public string DocumentType {get;private set;}
Now you can't create an instance without specifying the document type, and it can't be removed after that time. You could also allow the `set` but validate:
public YourType(string documentType) {
DocumentType = documentType;
}
private string documentType;
public string DocumentType {
get { return documentType; }
set {
// TODO: validate
documentType = value;
}
}
Problem
I have requirement in a custom class where I want to make one of my properties required. How can I make the following property required? ``` public string DocumentType { get { return _documentType; } set { _documentType = value; } } ```