Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a property required in c#?

Tags:

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;
    }
}
like image 573
Shailender Singh Avatar asked May 29 '12 06:05

Shailender Singh


2 Answers

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;
    }
}
like image 151
Marc Gravell Avatar answered Oct 19 '22 17:10

Marc Gravell


If you mean you want it always to have been given a value by the client code, then your best bet is to require it as a parameter in the constructor:

class SomeClass
{
    private string _documentType;

    public string DocumentType
    {
        get
        {
            return _documentType;
        }
        set
        {
            _documentType = value;
        }
    }

    public SomeClass(string documentType)
    {
        DocumentType = documentType;
    }
}

You can do your validation – if you need it – either in the property's set accessor body or in the constructor.

like image 43
Will Vousden Avatar answered Oct 19 '22 16:10

Will Vousden