Is there a possibility in C# to have an optional parameter be optionally required in specific situations and have it throw an error on compile time?
Let me explain with the code below as an example. The class ServiceResponse has a constructor accepting an enumeration value and an optional string. In case the enumeration value used to instantiate the class equals Error, the message becomes required. In the example code it will throw an ArgumentNullException when no message was supplied. Sadly this will only become visible on run time. However it should become visible on compile time so it warns the developer.
public class ServiceResponse
{
public ServiceResponse(ServiceResult result, string message = null)
{
Result = result;
Message = result == ServiceResult.Error ? message ?? throw new System.ArgumentNullException(nameof(message)) : message;
}
public string Message { get; }
public ServiceResult Result { get; }
}
public enum ServiceResult {
Ok,
NotFound,
Error
}