Setting the default value of a C# Optional Parameter

余生长醉 提交于 2019-11-27 09:01:39

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!