I'm trying to convert objects dynamically based on a method's parameter object type using this line of code:
Convert.ChangeType(parameter.Value, parameterType);
However when parameterType
is equivalent to DateTime?
or int?
, or any other nullable type, this conversion doesn't work.
Why does this conversion not work with nullable types, and is there a way to have it work with nullable types?
(Note: that this is all being done dynamically, so there is no way of knowing beforehand if the type will be nullable or not... unless the Type
class has a way of deciphering that and I could then implement some type of if (nullable object) { // do special conversion }
?)
EDIT:
Looking at this question: How to use Convert.ChangeType() when conversionType is a nullable int
I've tried implementing the following answer:
public static T GetValue<T>(string value)
{
Type t = typeof(T);
t = Nullable.GetUnderlyingType(t) ?? t;
return (value == null || DBNull.Value.Equals(value)) ?
default(T) : (T)Convert.ChangeType(value, t);
}
However this answer is used by doing something like:
string a = 24;
decimal? d = GetValue<decimal?>(a);
But in my case I don't necessarily know it will be of type decimal?
; I need to pass in the Type
of which I want to convert it to, for example I need to do something like:
Type parameterType = parameterDescriptor.ParameterType;
var unknownType = GetValue<parameterType>(parameter.Value);