شما میتونی یک Generic Exetension Method برای این کار به این صورت بنویسی:
public static class DictionaryExtensions
{
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
{
TValue value;
if (dictionary.TryGetValue(key, out value))
return value;
return default(TValue);
}
}
و بعد اینطوری ازش استفاده کنی:
Dictionary<string, int?> myDictionary = new Dictionary<string, int?>();
myDictionary.Add("First", 12);
int? firstValue = myDictionary.GetValueOrDefault("First");
int? undefinedValue = myDictionary.GetValueOrDefault("Hello");
اینطوری نه به نوع کلید و نه به نوع مقدار وابسته نیستید.