Skip to content

Instantly share code, notes, and snippets.

@lurumad
Last active August 29, 2015 14:01
Show Gist options
  • Save lurumad/4cce9ef5980809446c84 to your computer and use it in GitHub Desktop.
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>
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")
@eiximenis
Copy link

 // 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