Add to Collection if Not Null

I'd recommend writing an extension method:

public static class MyExtensions
{
    public static void AddIfNotNull<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
    {
        if ((object)value != null)
            dictionary.Add(key, value);
    }
}

Using (object)value != null ensures that this works as you'd expect with nullable types, (e.g. int?) value types, (e.g. int) and reference types (e.g. SomeClass). If you compare it to default(TValue), then an int of 0 will not be added, even though it's not null. If you include a TValue : class requirement, you can't use Nullable<T> as the type, which it sounds like is your most common usage.


You can make a method that hides your if:

AddIfNotNull(myDictionary, "...", myObject.whatever);

private static void AddIfNotNull<K,T>(
    IDictionary<K,T> myDictionary
,   K key
,   T value) {
    if (value != default(T)) {
        myDictionary.Add(key, value);
    }
}

You can earn some "points for style" by making the method an extension (you need to add it to a static class then):

private static void AddIfNotNull<K,T>(
    this IDictionary<K,T> myDictionary
,   K key
,   T value) {
    if (value != default(T)) {
        myDictionary.Add(key, value);
    }
}

myDictionary.AddIfNotNull(myDictionary, "...", myObject.whatever);

If you know that you are inserting only reference type objects, replace default(T) with null and add a class T constraint to the generic.


How about an extension method for your dictionary?

public static void AddIfNotNull<T,U>(this Dictionary<T,U> dic, T key, U value) 
where U : class {
    if (value != null) { dic.Add(key, value); }
}

You could then do this:

myDictionary.AddIfNotNull("...",myObject.whatever);

Tags:

C#

Nullable