With the following example, two calls are made to ConvertNumericStringObj, it sends back a Type int object both times.
string strValue = "123";
object obj = ConvertNumericStringObj(typeof(int), strValue);
object obj = ConvertNumericStringObj(typeof(int?), strValue);
public static object ConvertNumericStringObj(Type conversion, object value)
{
var t = conversion;
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return null;
}
t = Nullable.GetUnderlyingType(t);
}
return Convert.ChangeType(value, t);
}
My question is: Is there someway to pass in the string and int? Type and convert it so it returns a int? object?
Nullable<T>. The runtime has special boxing behavior for nullables. If an object reference is a boxedTthen it can always be converted to aT?.