How to assign null values to dynamic property type

Basically, I am in need of a converter which converts a DataReader object to generic type.

so when I do -

while(dataReader.HasRows()){
    var result= dataReader.ConvertToObject<MyModel>();
}

It calls an extension method of generic type -

public static T ConvertToObject<T>(this DbDataReader reader) where T : new()
{
    T res = new T();

    T t = new T();

    for (int inc = 0; inc < reader.FieldCount; inc++)
    {
        Type type = t.GetType();
        PropertyInfo prop = type.GetProperty(reader.GetName(inc));
        var value = reader.GetValue(inc);
        if (value == System.DBNull.Value)
        {
            value = null;
        }

        var targetType = IsNullableType(prop.PropertyType) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType;

        value = Convert.ChangeType(value, targetType);

        prop.SetValue(t, value, null);
    }

    res = t;
    return res;
}

private static bool IsNullableType(Type type)
{
    return type.IsConstructedGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
}

It works fine until the the result in datareader is System.DBNull except the System.String

To handle null values I forcefully checked if the value is type of System.DBNull then assign it a C# NULL object.

if (value == System.DBNull.Value)
{
    value = null;
}

This however fails the conversion when the result is null for numeric type object.

So basically I am trying to do is when the result value is type - System.Nullable[System.Decimal]

then

if (value == System.DBNull.Value)
{
  value = (System.Decimal?) null;
}

Or

value = (System.DateTime?)null //for DateTime
value = (System.Int32?)null //for Int32

What I tried to get dynamic property type

if (value == System.DBNull.Value)
{
    value = (prop.PropertyType ?) null; // to get it dynamic
}

This didn't work. Please let me know what I have to do?

Jon Skeet
people
quotationmark

You can't specify null as a value of type T because it might not be a valid value for T. (Think int etc.)

However, you can use default(T), which will be the default value for T - the same value you'd get if you left a field of type T uninitialized, for example. That will be:

  • For reference types, a null literal
  • For nullable value types, the null value of the type
  • For non-nullable value types, the "all zero" value (0 for all numeric values etc)

people

See more on this question at Stackoverflow