I have a simple value type MyTestStruct
which has one method called Parse
which attempts to convert a string into MyTestStruct
:
public struct MyTestStruct {
public readonly long UnderlyingValue;
public MyTestStruct(long underlyingValue)
{
UnderlyingValue = underlyingValuel
}
public static MyTestStruct Parse(string input) {
if (string.IsNullOrEmpty(input))
throw new ArgumentException("Value cannot be parsed because the string is either null or empty", nameof(input));
return new MyTestStruct(long.Parse(input));
}
}
VS 2019 has greeted me with the following warning:
Method 'MyTestStruct MyTestStruct.Parse(string input)' passes a literal string as parameter 'message' of a call to 'ArgumentException.ArgumentException(string message, string paramName)'. Retrive the following string(s) from a resource table instead: "Value cannot be parsed becase the string is either null or empty"'
Online search seem mostly focus on suppressing the warning but I would rather fixing it. Instead, I would like to be able to localize the string.
One solution would be to inject IStringLocalizer<MyTestStruct>
, but it seems a bit odd to have an extra dependency in the struct only to use it 'if things go wrong'. Especially, as this is not alawys possible (e.g. implict conversions, operators etc). IStringLocalizer<MyTestStruct>
can be mutable which is generally regarded as bad practice.
What would be the correct approach to take to fix this issue?