jeudi 18 mars 2021

Try/Can pattern vs return null [closed]

I have a wrapper that add/get return data from cache. There are two ways to make it in safely manner:

  • create bool TryAdd/TryGet methods that return true if operation succeeded and put value into output parameter, otherwise return false;
  • return value, or return null if not found.

What is preferable?

In fact I stuck with implementation of second method because Get<int>() and have this error. Is there a recommended approach to handle both value and reference types?

Cannot convert null to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead.

I saw the answer but it's not what I want, because default(int) can be valuable for me, so I need to know exact value including existence.

Aucun commentaire:

Enregistrer un commentaire