I have a generic function that I am using to retrieve key-value pair value from sqlite database.
The function signature is:
T Retrieve<T>(string key);
I want to return null whenever the key doesn't exist in the database. I could do this for reference types with this signature but can't do with value types
I could change the signature to object Retrieve(string key); and then cast it to type T but I was wondering if there is any other better method to achieve this.
There are competing factors here:
nullNullable<T> can be null, but that would be T? Retrieve<T>(string key) where T : struct, which would make it impossible for you to use Retreive<string>(...), which seems a likely use-caseSo; you can't have both of those. You way wish instead to consider reporting the result value and whether it was null separately, for example, one of:
bool TryRetrieve<T>(string key, out T value);
T Retrieve<T>(string key, out bool isNull);
(T value, bool isNull) Retrieve<T>(string key);
using default(T) as the value when null is encountered.
The advantage of the last one is that it also works for async, i.e.
async Task<(T value, bool isNull)> RetrieveAsync<T>(string key);
where-as out parameters do not work for most async scenarios.
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