Skip to content

Instantly share code, notes, and snippets.

@DTTerastar
Forked from defunkt/Dictionary lookup with default
Last active December 11, 2015 21:38
Show Gist options
  • Save DTTerastar/4663406 to your computer and use it in GitHub Desktop.
Save DTTerastar/4663406 to your computer and use it in GitHub Desktop.
public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key, TValue defaultVal = default(TValue))
{
TValue ret;
return dic.TryGetValue(key, out ret) ? ret : defaultVal;
}
public static TValue GetValueOrDefault<TValue>(this StateBag stateBag, string key, TValue defaultValue = default(TValue))
{
object value = stateBag[key];
return Equals(value, null) ? defaultValue : (TValue) value;
}
public static T GetValueOrDefault<T>(this NameValueCollection coll, string key, T defaultValue = default(T))
{
var value = coll.Get(key);
return value == null ? defaultValue : ChangeType<T>(value);
}
public static string ChangeType(string value)
{
return value;
}
public static T ChangeType<T>(string value)
{
if (String.IsNullOrEmpty(value))
return default(T);
Type type = typeof(T);
Type desiredType = Nullable.GetUnderlyingType(type) ?? type;
if (desiredType.IsEnum) return (T)Enum.Parse(desiredType, value, true);
return (T)Convert.ChangeType(value, desiredType);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment