ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

GetValueOrDefinedDefault

Given our dictionary retrieves the element with a given key defined in input. when this key is not defined, or the dictionary is null, or the key itself is null, then the default value also defined in input is returned

Source

public static TValue GetValueOrDefinedDefault<TKey, TValue>(this IDictionary<TKey, TValue> source, TKey key, TValue definedDefault)
{
    if (source == null || key == null)
        return definedDefault;

    var havingValue = source.TryGetValue(key, out var outValue);
    return havingValue ? outValue : definedDefault;
}

Example

myDictonary.GetValueOrDefinedDefault("Item", string.Empty);

Author: Enrico Meloni

Submitted on: 20 okt. 2023

Language: csharp

Type: System.Collections.Generic.IDictionary<TKey, TValue>

Views: 1218