hazelcast-csharp-client icon indicating copy to clipboard operation
hazelcast-csharp-client copied to clipboard

Add a bool TryGet(TKey key, out TValue value) method to IMap [API-2049]

Open drieseng opened this issue 6 years ago • 3 comments

Right now when the value of a map is a primitive (not-nullable) type, the following code must be used to verify if there's a value for a given key and subsequently get the value:

double GetTaxRate(IHazelcastInstance instance, int zipCode)
{
    var taxRates = instance.GetMap<int, double>("TaxRates");
    if (!taxRates.ContainsKey(zipCode))
    {
        throw new ArgumentException($"No tax rate defined for zip code '{zipCode}'.", nameof(zipCode));
    }

    return taxRates.Get(zipCode);
}

I propose to introduce a bool TryGet(TKey key, out TValue value) method on IMap. This would:

  • Save a roundtrip to the server.
  • Eliminate a concurrency issue between the ContainsKey(...) and Get(...).
double GetTaxRate(IHazelcastInstance instance, int zipCode)
{
    var taxRates = instance.GetMap<int, double>("TaxRates");
    if (!taxRates.TryGet(zipCode, out var taxRate))
    {
        throw new ArgumentException($"No tax rate defined for zip code '{zipCode}'.", nameof(zipCode));
    }

    return taxRate;
}

drieseng avatar Sep 27 '18 06:09 drieseng