views:

232

answers:

6

I want to serialize a nullable bool simply by converting it to a string

    public static string SerializeNullableBoolean(bool? b)
    {
        if (b == null)
        {
            return "null or -1 or .."; // What to return here?
        }
        else
        {
            return b.ToString();
        }
    }

What is the most appropriate string to serialize the null-value as?

+2  A: 

I would choose an empty string to represent the null-value.

Hans Kesting
+2  A: 

If you're returning True/False for real bool values, you should return Null for symmetry's sake in case b is null.

Blindy
+5  A: 

Since bool.ToString() returns "True" or "False", I would go with "Null". I would also rewrite this as:

return b.HasValue ? b.ToString() : "Null";

Edit: I take that back. bool?.ToString() returns empty string, so I would decide based on what's more convenient. If a person needs to read the output then "Null" is a better choice; if it only needs to be used in code then empty string is fine. If you go with empty string it is as simple as:

return b.ToString();
Jamie Ide
+1  A: 

Be consistent.

b.ToString()

returns the strings 'true' or 'false'. Thus if you return -1 it will be less consistent if you actually read the serialized files. The deserialization code will also become more "ugly" and less readable.

I would choose to serialize it to either the string 'unset' (or something along those lines) or the string 'null'. Unless you have really strict space requirements or really huge datasets to serialize the extra characters shouldn't really matter.

wasatz
+5  A: 

Why not:

b.ToString()

If b is null, then it returns an empty string. Since that's what the framework returns, I would use it to be consistent. This is also what XmlSerializer uses for nullable scalars.

Keltex
+1  A: 

If you are using the built in XmlSerializer you can also do the following to serialize the value (and prevent a lot of ugly custom serialization code):

    [Serializable]
    public class Foo
    {
        [XmlIgnore]
        public bool? Bar { get; set; }

        [XmlAttribute("Bar")]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public string xmlBar
        {
            get { return Bar.ToString(); }
            set
            {
                if (string.IsNullOrEmpty(value)) Bar = null;
                else Bar = bool.Parse(value);
            }
        }
    }
Gord
I actually didn't check to see if the XmlSerializer will correctly handle a nullable bool, so this may be unneeded.
Gord