Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Less wrong TryGetValue then null check syntax

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.

like image 226
Randy Hall Avatar asked Dec 06 '25 19:12

Randy Hall


2 Answers

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"
like image 93
Evk Avatar answered Dec 08 '25 08:12

Evk


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
    ...
}
like image 45
mjwills Avatar answered Dec 08 '25 08:12

mjwills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!