I am trying to make a super cool extension for IDictionary
- GetValue
with a default value that is null if not set. Here is the code I came up with (doesn't work):
public static TValue GetValue<TKey, TValue> (this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = null)
{
TValue value;
return dictionary.TryGetValue(key, out value)
? value
: defaultValue;
}
How to make this for nullables
only? (like, don't include int
, etc).
You mean for reference types
only. Add where T: class
as follows:
public static TValue GetValue<TKey, TValue> (this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = null)
where TValue: class
{
However you can make this work with value types too, by using default(TValue)
to specify the default:
public static TValue GetValue<TKey, TValue>(this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = default(TValue))
{
TValue value;
return dictionary.TryGetValue(key, out value)
? value
: defaultValue;
}
Of course, only do this if you actually WANT it to work with all possible types, rather than just with reference types.
You can use constraints on your type parameters ( MSDN Type Constraints ). What you want here is the class
constraint, like so:
public static TValue GetValue<TKey, TValue> (this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = null) where TValue : class
This works for reference types, which is what you really want. Nullable would imply something like int?
working as well.
Use the class constraint :
public static TValue GetValue<TKey, TValue> (this IDictionary<TKey,
TValue> dictionary, TKey key, TValue defaultValue = null) where TValue : class
{
TValue value;
return dictionary.TryGetValue(key, out value)
? value
: defaultValue;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.