demo stack
demo stack

Reputation: 103

Code giving warning with CultureInfo

I have an code which displays me a warning like :

Because the behavior of 'string.Format(string, object, object)' could vary based on the current user's locale settings, replace this call in 'MethodName' with a call to 'string.Format(IFormatProvider, string, params object[])'. If the result of 'string.Format(IFormatProvider, string, params object[])' will be displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider' parameter. Otherwise, if the result will be stored and accessed by software, such as when it is persisted to disk or to a database, specify 'CultureInfo.InvariantCulture'.

The code for it is

string[] l_array = (from key in nameValueCollection.AllKeys
                    from value in nameValueCollection.GetValues(key)
                    select $"{(key)}={(value)}").ToArray();
return string.Join("&", l_array);

I think I can write culture Info, but where and why I require that ? Or what else should I change.

Upvotes: 3

Views: 11841

Answers (2)

juharr
juharr

Reputation: 32276

String interpolation (when you use $ before a string) is just syntactic sugar for a string.Format call and the compiler will basically replace it with one. You can switch to using the overload of string.Format that takes a IFormatProvider instead to fix the warning.

string[] l_array = (from key in nameValueCollection
                    from value in nameValueCollection.GetValues(key)
                    select string.Format(
                        CultureInfo.InvariantCulture, 
                        "{0}={1}", 
                        key, 
                        value)).ToArray();
return string.Join("&", l_array);

Upvotes: 3

Gilgamesh
Gilgamesh

Reputation: 668

Edit, it looks like doing $"{{key}}={{value}}".ToString(CultureInfo.InvariantCulture) doesn't work, i've updated my solution.

You can remove this warning with the following:

string[] l_array = (from key in nameValueCollection.AllKeys
                from value in nameValueCollection.GetValues(key)
                select InvariantCulture($"{(key)}={(value)}"))
               .ToArray();


   ...
   public static string InvariantCulture(IFormattable formattable)
    {
        return formattable.ToString(null, CultureInfo.InvariantCulture);
    }

Upvotes: 3

Related Questions