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?
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();
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.
If you're returning True/False for real bool
values, you should return Null for symmetry's sake in case b
is null
.
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.
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