Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the default value of a C# Optional Parameter

Tags:

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.

like image 416
Jaxidian Avatar asked Apr 28 '10 13:04

Jaxidian


People also ask

What is the default value of C?

value − Any value to initialize the variable. By default, it is zero.

What is the default value of int in C?

The default value of Integer is 0.

Are there default parameters in C?

There are no default parameters in C. One way you can get by this is to pass in NULL pointers and then set the values to the default if NULL is passed.


2 Answers

One option is to make the default value null and then populate that appropriately:

public void ValidationError(string fieldName, string message = null) {     string realMessage = message ?? ValidationMessages.ContactNotFound;     ... } 

Of course, this only works if you don't want to allow null as a genuine value.

Another potential option would be to have a pre-build step which created a file full of const strings based on the resources; you could then reference those consts. It would be fairly awkward though.

like image 52
Jon Skeet Avatar answered Oct 13 '22 03:10

Jon Skeet


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.

like image 23
Tom Cabanski Avatar answered Oct 13 '22 04:10

Tom Cabanski