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?
To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false. Boolean values are not actually stored in Boolean variables as the words “true” or “false”.
The INI file consists of sections and keys. The name of a section in the *. ini file is always entered inside the square brackets. Each section contains several keys (the key must be always assigned to the section that begins in the file before this key).
An INI file is a configuration file for computer software that consists of a text-based content with a structure and syntax comprising key–value pairs for properties, and sections that organize the properties.
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 returnTrue
, and'0'
,'no'
,'false'
, and'off'
, which cause it to returnFalse
.
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:
1
and 0
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With