Search code examples
c#.netclr

Stipulating that a property is required in a class - compile time


Is there a way to stipulate that the clients of a class should specify a value for a set of properties in a class. For example (see below code), Can i stipulate that "EmploymentType" property in Employment class should be specified at compile time? I know i can use parametrized constructor and such. I am specifically looking for outputting a custom warning or error during compile time. Is that possible?

public class Employment
{
   public EmploymentType EmploymentType {get; set;}
}

public enum EmploymentType
{
    FullTime = 1,
    PartTime= 2
}

public class Client
{
    Employment e = new Employment();
// if i build the above code, i should get a error or warning saying you should specify value for EmploymentType
}

Solution

  • As cmsjr stated what you need to do is this:

    public class Employment
    {
        public Employment(EmploymentType employmentType)
        {
            this.EmploymentType = employmentType;
        }
    
        public EmploymentType EmploymentType { get; set; }
    }
    

    This will force callers to pass in the value at creation like this:

    Employment e = new Employment(EmploymentType.FullTime);
    

    In the situation where you need to have a default constructor (like serialization) but you still want to enforce the rule then you would need some sort of state validation. For instance anytime you attempt to perform an operation on the Employment class you can have it check for a valid state like this:

    public EmploymentType? EmploymentType { get; set; } // Nullable Type
    
    public void PerformAction()
    {
        if(this.Validate())
            // Perform action
    }
    protected bool Validate()
    {
        if(!EmploymentType.HasValue)
            throw new InvalidOperationException("EmploymentType must be set.");
    }
    

    If you're looking throw custom compiler warnings, this is not exactly possible. I asked a similar question here Custom Compiler Warnings