Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize Nullable<bool>?

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?

like image 420
Gustaf Carleson Avatar asked Mar 09 '10 15:03

Gustaf Carleson


4 Answers

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();
like image 192
Jamie Ide Avatar answered Nov 17 '22 02:11

Jamie Ide


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.

like image 40
Keltex Avatar answered Nov 17 '22 02:11

Keltex


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

like image 2
Blindy Avatar answered Nov 17 '22 02:11

Blindy


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.

like image 2
wasatz Avatar answered Nov 17 '22 02:11

wasatz