How to make a property required in C#?

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;
    }
}

Leave a Comment