Alex Rivera | Logout

Setting the default value of a C# optional parameter

Asked 2010-04-28T13:07:16.287
26

Whenever I attempt to set the default value of an optional parameter to something in a resource file, I get a compile-time error of:

Default parameter value for 'message' must be a compile-time constant.

Is there any way that I can change how the resource files work to make this possible?

public void ValidationError(string fieldName, 
                            string message = ValidationMessages.ContactNotFound)

In this, ValidationMessages is a resource file.

Edit
Report

2 Answers

14

Another option is to split your method into two, and have the one overload call the other, like so:

public void ValidationError(string fieldName)
{ 
    ValidationError(fieldName, ValidationMessages.ContactNotFound);
}

public void ValidationError(string fieldName, string message)
{
    ...
}

This way also enables you to pass null as a value for message in case that is also a valid value for that parameter.

answered 2012-02-19T12:16:37.740
13

No, you will not be able to make the resource work directly in the default. What you need to do is set the default value to something like null and then do the resource lookup when the parameter has the default value in the body of the method.

answered 2010-04-28T13:08:58.627

Your Answer