Search code examples
c#asp.net-coretostringculturetolower

.ToString() and .ToLower() gives warning about culture differences


I am storing some boolean values as string session variables, like this:

HttpContext.Session.SetString("SomeBool", user.SomeBool.ToString().ToLower());

This gives me warnings that the result could vary depending on the users culture. How is that possible? In what way could the result of ToString() or ToLower() of "True" or "False" vary depending on culture? Aren't boolean values always represented by the English words "True" and "False", no matter the culture of the database or hosting environment?

I've also tried these three, which all gives exactly the same warning:

HttpContext.Session.SetString("SomeBool", FormattableString.Invariant($"{user.SomeBool.ToString().ToLower()}"));

HttpContext.Session.SetString("SomeBool", String.Format(CultureInfo.CurrentCulture, $"{0}", user.SomeBool.ToString().ToLower()));

HttpContext.Session.SetString("SomeBool", String.Format(CultureInfo.CurrentCulture, user.SomeBool.ToString().ToLower()));

VS suggests I can disable CA1305 warnings, but I don't want to do that.

Any suggestions?

Update

Although VillageTech's answer answers my question, I have changed my code to avoid the issue altogether. Inspired by Christopher's suggestion about hard coding the values:

HttpContext.Session.SetString("SomeBool", user.SomeBool ? "true" : "false");

Solution

  • Both ToString() and ToLower() can emit such warnings. Use this:

    HttpContext.Session.SetString("SomeBool", user.SomeBool.ToString(CultureInfo.CurrentCulture).ToLower(CultureInfo.CurrentCulture));