Click here to Skip to main content
11,568,522 members (42,976 online)
Click here to Skip to main content

Dictionary Extensions: Define useful extensions to play safe

, 25 Jan 2012 CPOL 16.5K 1
Rate this:
Please Sign up or sign in to vote.
Useful extensions to play safe.
if (searchCriteria.ContainsKey(key) &&
       !string.IsNullOrEmpty(searchCriteria[key]))
    searchTerm = searchCriteria[key];

Ever have a dictionary or similar data structure and your code has many repeated checks to pull the value when in reality you’d be happy with a default value like null or string.Empty? Well, consider the following extension to Dictionary:

public static class DictionaryExtensions
{
    public static TValue GetSafeValue<TKey, TValue>(this Dictionary<TKey, 
                         TValue> dictionary, TKey key)
    {
        TValue result = default(TValue);
        dictionary.TryGetValue(index, out result);
        return result;
    }
}

Let’s you do:

Dictionary bob = new Dictionary();
string safe = bob.GetSafeValue(100);
System.Diagnostics.Trace.WriteLine(safe);

where safe defaults to “” as it hasn’t been added. Stop! I know what you’re going to say and I thought of that too. You can control the default value as well:

public static class DictionaryExtensions
{
    /// <span class="code-SummaryComment"><summary>
</span>    /// Gets the safe value associated with the specified key.
    /// <span class="code-SummaryComment"></summary>
</span>    /// <span class="code-SummaryComment"><typeparam name="TKey">The type of the key.</typeparam>
</span>    /// <span class="code-SummaryComment"><typeparam name="TValue">The type of the value.</typeparam>
</span>    /// <span class="code-SummaryComment"><param name="dictionary">The dictionary.</param>
</span>    /// <span class="code-SummaryComment"><param name="key">The key of the value to get.</param>
</span>    public static TValue GetSafeValue<TKey, TValue>(this Dictionary<TKey, 
                         TValue> dictionary, TKey key)
    {
        return dictionary.GetSafeValue(key, default(TValue));
    }

    /// <span class="code-SummaryComment"><summary>
</span>    /// Gets the safe value associated with the specified key.
    /// <span class="code-SummaryComment"></summary>
</span>    /// <span class="code-SummaryComment"><typeparam name="TKey">The type of the key.</typeparam>
</span>    /// <span class="code-SummaryComment"><typeparam name="TValue">The type of the value.</typeparam>
</span>    /// <span class="code-SummaryComment"><param name="dictionary">The dictionary.</param>
</span>    /// <span class="code-SummaryComment"><param name="key">The key of the value to get.</param>
</span>    /// <span class="code-SummaryComment"><param name="defaultValue">The default value.</param>
</span>    public static TValue GetSafeValue<TKey, TValue>(this Dictionary<TKey, 
           TValue> dictionary, TKey key, TValue defaultValue)
    {
        TValue result;
        if (key == null || !dictionary.TryGetValue(key, out result))
            result = defaultValue;
        return result;
    }
}

Let’s you do:

Dictionary bob = new Dictionary();
string safe = bob.GetSafeValue(100, null);
System.Diagnostics.Trace.WriteLine(safe);

where safe is null.

There’s obviously something wrong with me because I still think this stuff is cool.

I’m developing a nice little set of extensions at this point. Often it seems like overkill to encapsulate handy functions like these in a class. I had started by deriving a class from Dictionary<TKey, TValue> but changed over to the above.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Chris_Green
Architect Avaya Inc.
Ireland Ireland
Formerly a C++ client developer, nowadays I'm all about C# and ASP.NET. Over the years I have mastered some and played with many aspects of .NET.

Follow my blog as I catalogue the more arcane problems I encounter and their solutions at CodingLifestyle.com

You may also be interested in...

Comments and Discussions

 
QuestionIf you really want your methods to be "safe"... Pin
Qwertie24-Jan-12 16:07
memberQwertie24-Jan-12 16:07 
AnswerRe: If you really want your methods to be "safe"... Pin
newkie25-Jan-12 2:35
membernewkie25-Jan-12 2:35 
QuestionNaming Pin
Richard Deeming24-Jan-12 6:45
memberRichard Deeming24-Jan-12 6:45 
QuestionGood code! Pin
Member 308248723-Jan-12 20:58
memberMember 308248723-Jan-12 20:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150624.2 | Last Updated 25 Jan 2012
Article Copyright 2012 by Chris_Green
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid