An annoying behaviour of ProtoBuff.net is that empty collections are serialised as null
. This can create some pretty hard to pin down bugs.
Retrieval of cached values from my application is done with the following function:
public T Get<T>(string cacheKey)
{
var data = (byte[])Database.StringGet(cacheKey);
if (data == null)
{
return default(T);
}
return Serialiser.Deserialise<T>(data);
}
If T
is List<int>
with zero values, this will return an empty list (because data == null
it will return default(List<int>)
).
If T
is Dictionary<bool, Hashset<int>
, where two keys true
and false
exist but there are no values in the corresponding hashset, the key exists but the value is null
.
Is there any way to determine if T
contains a collection, and if so return an empty collection instead of null if the collection is empty? Preferably, it would check for an empty collection anywhere in the object, not just if T itself is a collection that contains a collection.
The alternative (that I'm doing now) is to try to remember to check for nulls when I know the explicit type when I get from cache which isn't ideal.