Skip to content

Commit

Permalink
Fix DataRowExtensions.Field for nullable types
Browse files Browse the repository at this point in the history
Fixes dotnet/corefx#41879


Commit migrated from dotnet/corefx@f664740
  • Loading branch information
roji committed Nov 4, 2019
1 parent 26970f6 commit ea9be74
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -147,25 +147,30 @@ private static class UnboxT<T>

private static Converter<object, T> Create()
{
if (default(T) == null)
return ReferenceOrNullableField;
else
return ValueField;
}
if (typeof(T).IsValueType)
{
return typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>)
? (Converter<object, T>)Delegate.CreateDelegate(
typeof(Converter<object, T>),
typeof(UnboxT<T>)
.GetMethod("NullableField", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic)
.MakeGenericMethod(typeof(T).GetGenericArguments()[0]))
: ValueField;
}

private static T ReferenceOrNullableField(object value)
{
return ((DBNull.Value == value) ? default(T) : (T)value);
return ReferenceField;
}

private static T ReferenceField(object value)
=> value == DBNull.Value ? default : (T)value;

private static T ValueField(object value)
{
if (DBNull.Value == value)
{
throw DataSetUtil.InvalidCast(SR.Format(SR.DataSetLinq_NonNullableCast, typeof(T)));
}
return (T)value;
}
=> value == DBNull.Value
? throw DataSetUtil.InvalidCast(SR.Format(SR.DataSetLinq_NonNullableCast, typeof(T)))
: (T)value;

private static Nullable<TElem> NullableField<TElem>(object value) where TElem : struct
=> value == DBNull.Value ? default : new Nullable<TElem>((TElem)value);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,23 @@ public void Field_ColumnVersion_NullColumnThrows()
AssertExtensions.Throws<ArgumentNullException>("column", () => DataRowExtensions.Field<int>(row, column: null, version: DataRowVersion.Default));
}

[Fact]
public void Field_Nullable_Enum()
{
DataTable table = new DataTable("test");
table.Columns.Add(new DataColumn("col", typeof(int)));
DataRow row = table.NewRow();
row["col"] = 0;
table.Rows.Add(row);

Assert.Equal(SomeEnum.Foo, table.Rows[0].Field<SomeEnum?>("col"));
}

enum SomeEnum
{
Foo
}

[Fact]
public void SetField_IndexValue_NullRowThrows()
{
Expand Down Expand Up @@ -170,7 +187,5 @@ public void SetField_ColumnValue_NullValueReplacedByDBNull()
DataRowExtensions.SetField<string>(row, column: column, value: null);
Assert.Equal(DBNull.Value, row[column]);
}


}
}

0 comments on commit ea9be74

Please sign in to comment.