36

I've seen a variety of ways used to set boolean values in INI files:

  • variable = true
  • variable = 1
  • variable = on
  • variable = yes

Which is the most canonical, common, and/or preferred way?

Anirvan
  • 6,214
  • 5
  • 39
  • 53

2 Answers2

22

There's no spec for INI files, but for whatever it's worth, I'll list the behaviour of a few implementations from languages I know.

Python's built-in configparser module offers a getboolean that behaves as follows:

the accepted values ... are '1', 'yes', 'true', and 'on', which cause this method to return True, and '0', 'no', 'false', and 'off', which cause it to return False.

In PHP's parse_init_file, on the other hand:

String values "true", "on" and "yes" are converted to TRUE. "false", "off", "no" and "none" are considered FALSE.

Meanwhile, .NET has no built-in support for INI parsing, but its most popular INI-parsing library, ini-parser, offers no support whatsoever for automatic parsing of values and returns them all as strings. Its Getting Started examples show parsing booleans with .NET's Boolean.Parse, which will accept the strings "true" and "false" (with any capitalisation) and throw an exception if given anything else.

In summary: there is absolutely no consistency on this question between different implementations of INI parsers.

I would recommend:

  • If you are only going to parse your INI using a single parser, check how that parser behaves and craft your INI to suit its particular implementation.
  • If you need to support a wide range of parsers (for example, for language interoperability), then either abandon INI as a format entirely, or else entirely avoid using any of the magic boolean values that some parsers understand and instead stick to 1 and 0.
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
  • Ironically, I just discovered Delphi's implementation expects `1`/`0` - I'm a bit surprised `true`/`True`/`false`/`False` don't work. Neither does `yes`/`no`. Seems problematic, if you want apps written in different languages to share the same INI file... – Jerry Dodge Jul 29 '18 at 14:18
5

It depends on the parser of the ini file. The values are always strings.

true/false : In C# I can convert true and false strings directly to bool. Equals readability and easy conversion. less code.

0/1 : I have to convert string 0 and 1 to int before converting to bool. Smaller ini file size. Less readable. more code.

yes/no and on/off I would have to use a if/switch statement. readable. more code.

My preferred way is true/false. Object serialize to true/false, you can use true/false with the sql bit type even though it stores as 0/1. So the only down side would be size which can be minor in most contexts.

Valamas
  • 24,169
  • 25
  • 107
  • 177