Less wrong TryGetValue then null check syntax

8.9k Views Asked by At

I'm a little new to C# still... I'm finding myself reusing a specific procedure over and over. Before I go writing a helper method for personal laziness, is there a shorter or less wrong way to write this sort of statement?

Dictionary<string, string> data = someBigDictionary;
string createdBy;
data.TryGetValue("CreatedBy", out createdBy);
//do that for 15 other values
...
MyEntity me = new MyEntity{
    CreatedBy = createdBy ?? "Unknown",
    //set 15 other values
    ...
}

Essentially, set a property on an object by trying to get a value, then if it's null use a default value. I have a LOT of properties, it would be better if I could just

MyEntity me = new MyEntity{
    CreatedBy = TryToGetValueOrReturnNull(data, "CreatedBy") ?? "Unknown",
    ...
}

Again, I am perfectly capable of writing my own helper function. I'm looking for an existing native functionality or shorthand before I do so.

3

There are 3 best solutions below

2
Evk On BEST ANSWER

There are many similar questions (like this and this) which propose different solutions from extension methods to inheriting from dictionary and overriding indexer. However they are written before C# 7, and with C# 7 you can do this in one line:

CreatedBy = data.TryGetValue("CreatedBy", out var value) ? value : "Unknown"
0
mjwills On
public static class DictionaryExtensions
{
    public static U TryGetValueOrDefault<T, U>(this IDictionary<T, U> dict, T key, U defaultValue)
    {
        U temp;

        if (dict.TryGetValue(key, out temp))
            return temp;

        return defaultValue;
    }
}

then do something like:

Dictionary<string, string> data = someBigDictionary;
//do that for 15 other values
...
MyEntity me = new MyEntity{
    CreatedBy = data.TryGetValueOrDefault("CreatedBy", "Unknown"),
    //set 15 other values
    ...
}
0
Ofir Winegarten On

TryGetValue returns a bool indicating if the key was found in the dictionary. So you should use that and set the variable to the default if it was not found:

string createdBy;
if (!data.TryGetValue("CreatedBy", out createdBy)) createdBy="Unknown";