Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve value type values from generic function?

Tags:

c#

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.

like image 380
Monku Avatar asked Apr 22 '26 23:04

Monku


1 Answers

There are competing factors here:

  • regular value-types can't be null
  • Nullable<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-case

So; 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.

like image 77
Marc Gravell Avatar answered Apr 24 '26 11:04

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!