HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Adding to a dictionary and skipping duplicate keys

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
duplicateaddingkeysskippinganddictionary

Problem

What is the cleanest way to use dictionaries and protect against an unhandled ArgumentException if the key already exists in the dictionary?

I'd like to say that I can always guarantee uniqueness upstream, but I'm dealing with legacy code and mildly corrupt data from an old bug in the system.

I find myself using this pattern frequently but wonder if there is a better way.

public void AddToDictionaryContainsKey(Dictionary myDictionary, int myKey, string myValue )
{
    if (!myDictionary.ContainsKey(myKey))
    {
        myDictionary.Add(myKey, myValue);
    }
}


Maybe a try/catch block - but this seems less readable. The advantage is that if I ever do decide to log the problem I have a place to do it.

public void AddToDictionaryTryCatch(Dictionary myDictionary, int myKey, string myValue)
{
    try
    {
        myDictionary.Add(myKey, myValue);
    }
    catch (ArgumentException e)
    {
        // keep on truckin'
    }
}


The dictionaries are relatively small (typically < 1000 entries) so I prefer readability over performance.

Solution

Generating and handling exceptions is considered to be an expensive operation, so if(! x.ContainsKey()) is better. Yeah, the code example I see in MSDN uses try/catch but that's to illustrate the exception not advocate that as "best practice." Documentation I've read is pretty adamant about not throwing exceptions needlessly.

And you don't need try/catch to trap the duplicate key; just an else to the above if.

Context

StackExchange Code Review Q#124309, answer score: 15

Revisions (0)

No revisions yet.