2

So it appears that Convert.ToBoolean(string, IFormatProvider) completely ignores the given IFormatProvider.

ReferenceSource seems to agree:

public static bool ToBoolean(String value, IFormatProvider provider) {
    if (value == null)
        return false;
    Boolean.Parse(value);
}

but, despite this, the documentation advertises the behavior one would expect. No, this is not true: as @tyranid pointed out, I'm going blind.

Digging further, there exists the Convert.ToBoolean(object, IFormatProvider) overload, which invokes IConvertible.ToBoolean(IFormatProvider) on the given value. Bingo, right? Just box the value and you're golden.

Sadly, though, System.String's implementation of that method is as follows:

bool IConvertible.ToBoolean(IFormatProvider provider) {
    return Convert.ToBoolean(this, provider);
}

so we're back to where we started.

This seems like a huge oversight in a framework that otherwise is generally coherent.

Maybe it's a harder problem that one would imagine?

More importantly: do any of you know of a workaround? Is one supposed to handle all the different possible truthy and falsy values with a huge switch?

Oddly enough, either my Google-fu is getting rusty, or this issue has not been debated much.

Community
  • 1
  • 1
s.m.
  • 7,895
  • 2
  • 38
  • 46
  • I remember spelunking in ReferenceSource to the Convert class (long time ago) and finding out that some parameter was being ignored (I can't remember if this was the function I found, but I do remember it was Convert). So you are not alone. I can only guess, that trying to "fix" this bug could potentially break code that relied on this "broken" behavior. – Andre Feb 07 '17 at 08:27
  • 2
    The page you linked explicitly states for the provider "An object that supplies culture-specific formatting information. This parameter is ignored." so seems it is documented, just badly. – tyranid Feb 07 '17 at 09:30
  • @tyranid thanks, edited the question. I guess there's nothing to do then. Write an answer for posterity if you want, I'll mark it as accepted. – s.m. Feb 07 '17 at 09:45
  • Converting text to a boolean value is a pain in the ass to begin with. In our code bases, I'm pretty obstinate about using `"1" == value` and leaving it at that. Occasionally someone complains and demands that I support `true` -- no guesses for how I do that. I prefer predictability to the vagaries of `Convert`, especially for something specialized like `Boolean` (which innocent end users would be expected to enter only very rarely, and then not in a locale-specific format). – Jeroen Mostert Feb 07 '17 at 10:17

0 Answers0