Last active
August 29, 2015 14:01
-
-
Save lurumad/4cce9ef5980809446c84 to your computer and use it in GitHub Desktop.
Avoid repetitive use of ternary operation when we work with IDictionary<string, object>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static T GetValue<T>(this IDictionary<string, object> dictionary, string key) | |
{ | |
if (!dictionary.ContainsKey(key)) | |
{ | |
return default(T); | |
} | |
object data = dictionary[key]; | |
return data != null && data.GetType() == typeof (T) ? (T) data : default(T); | |
} | |
var path = dictionary.GetValue<string>("Path") |
// Si quieres protegerte de posibles Casts inválidos
public static T GetValue<T>(this IDictionary<string, object> dictionary, string key)
{
if (!dictionary.ContainsKey(key))
{
return default(T);
}
object data = dictionary[key];
return data != null && data.GetType() == typeof (T) ? (T) data : default(T);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
public class Program
{
static void Main(string[] args)
{
var dict = new Dictionary<string, object>();
dict.Add("1", new Task(()=>Task.Delay(10)));
dict.Add("2", 4);
dict.Add("5", 5);
dict.Add("6", 7);