How to Convert a String to a Nullable Type Which is Determined at Runtime?
There are two problems.
Firstly, Convert.ChangeType
just plain does not support nullable types.
Secondly, even if it did, by boxing the result (assigning it to an object
), you'd already be converting it to a DateTime
.
You could special case nullable types:
string s = "2012-02-23 10:00:00";Type t = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");object d;if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)){ if (String.IsNullOrEmpty(s)) d = null; else d = Convert.ChangeType(s, t.GetGenericArguments()[0]);}else{ d = Convert.ChangeType(s, t);}
I wrote the below generic helper method which works in most scenarios (not tested with generic types):
static void Main(string[] args){ Object result = ConvertValue( "System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", "2012-02-23 10:00:00");}public static Object ConvertValue(string typeInString, string value){ Type originalType = Type.GetType(typeInString); var underlyingType = Nullable.GetUnderlyingType(originalType); // if underlyingType has null value, it means the original type wasn't nullable object instance = Convert.ChangeType(value, underlyingType ?? originalType); return instance;}
public static T GetValue<T>(string Literal, T DefaultValue) { if (Literal == null || Literal == "" || Literal == string.Empty) return DefaultValue; IConvertible obj = Literal; Type t = typeof(T); Type u = Nullable.GetUnderlyingType(t); if (u != null) { return (obj == null) ? DefaultValue : (T)Convert.ChangeType(obj, u); } else { return (T)Convert.ChangeType(obj, t); } }