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")
@Jtorrecilla
Copy link

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);

        Console.WriteLine(dict.GetValue<string, object>("1").ToString());

        Console.ReadKey();
    }
}

public static class DictionaryExtensions
{
    public static T1 GetValue<T, T1>(this Dictionary<T, T1> dictionary, T key)
    {
        return dictionary[key] != null ? dictionary[key] : default(T1);
    }
}

@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