Huma Ali Huma Ali - 1 year ago 134
C# Question

Error in declaring default parameters for method

I am using default parameters but I'm getting error

Default parameter value for 'regularExpression' must be a compile time

Here is the method signature:

public static PIPE.DataTypes.BuyFlow.Entities.Question GetEmailAddressQuestion(string regularExpression = RegularExpressions.EmailAddressRegex, int rank = 1, bool isRequired = true)

And here is the property:

public static string EmailAddressRegex
get {
string emailAddressRegex = @"^[A-Za-z0-9\._%\+\-]+@([A-Za-z0-9\-]{1,40}\.)+([A-Za-z0-9]{2,4}|museum)$";
return emailAddressRegex;

Answer Source

It is like the error message says. Default parameters have to be constants (at compile time).

The Getter of EmailAddressRegex could return different values during runtime. That this is always the same value is not known to the compiler.

So change the EmailAddressRegex to a const string than the compiler error will be gone.


public const string EmailAddressRegex = @"^[A-Za-z0-9\._%\+\-]+@([A-Za-z0-9\-]{1,40}\.)+([A-Za-z0-9]{2,4}|museum)$";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download