Shailender Singh Shailender Singh - 24 days ago 17
C# Question

How to make a property required in c#?

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

Answer

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