This should do exactly what you need. If the requested type is a type with a null value, check the base type before casting.
public static T GetValue<T>(string key) { object o; if (Contents.TryGetValue(key, out o)) { if (o is T || Nullable.GetUnderlyingType(typeof(T)) == o.GetType()) { return (T)o; } } return default(T); }
My test code is:
Contents.Add("a string", "string value"); Contents.Add("an integer", 1); Contents.Add("a nullable integer", new Nullable<int>(2));
Results:
GetValue<string>("a string") = string value GetValue<int>("an integer") = 1 GetValue<int?>("a nullable integer") = 2 GetValue<object>("a string") = string value GetValue<object>("an integer") = 1 GetValue<object>("a nullable integer") = 2 GetValue<int?>("an integer") = 1 GetValue<int>("a nullable integer") = 2 GetValue<double>("a string") = 0 GetValue<double?>("a string") = GetValue<StringBuilder>("a string") =
source share