C# Return Results of Dictionary Lookup or if NULL return something else

Here is my current function (it works but wondering if there is a cleaner way to do it).

public static Dictionary<int, double> profileNetworkLowCostPriorityList;

public static double DetermineNetworkSortOrderValue(int network, double fee)
{
    if (profileNetworkLowCostPriorityList == null) return fee;
    if (profileNetworkLowCostPriorityList[network] != null) return profileNetworkLowCostPriorityList[network];
    return fee;
}

Basically, if the Dictonary object is not null and there was something found in the dictonary, return that something. If not, return something else. My concern is in referencing a null dictionary object and that throwing an error. I can of course catch the error and return something but not sure if that is the best approach.

This code will run up to hundreds of millions of times for each "widget" we process so looking for an "efficient way" to do this.

Jon Skeet
people
quotationmark

It sounds like you just want TryGetValue, basically:

public static double DetermineNetworkSortOrderValue(int network, double fee)
{
    double dictionaryFee;
    return profileNetworkLowCostPriorityList == null ||
        !profileNetworkLowCostPriorityList.TryGetValue(network, out dictionaryFee)
        ? fee : dictionaryFee;
}

Also note that your current code doesn't work at the moment - if there's no dictionary entry for the network, an exception will be thrown. You should also be seeing a compile-time warning like this:

The result of the expression is always 'true' since a value of type 'double' is never equal to 'null' of type 'double?'

Don't ignore warnings like that. I'd also strongly advise you not to expose public fields...

people

See more on this question at Stackoverflow