Setting the default value of a C# Optional Parameter

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.

Leave a Comment