Skip to content

Commit 5833b0b

Browse files
committed
Using GetValueOrDefault and skipping null check when mapping from nullable T to T
1 parent 092b891 commit 5833b0b

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

AgileMapper.UnitTests/WhenViewingMappingPlans.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,7 @@ public void ShouldNotRangeCheckNullableToNonNullableValues()
264264
string plan = Mapper.GetPlanFor<PublicField<int?>>().ToANew<PublicField<int>>();
265265

266266
plan.ShouldNotContain("int.MinValue");
267+
plan.ShouldNotContain("Value.HasValue");
267268
}
268269

269270
[Fact]

AgileMapper/Extensions/ExpressionExtensions.cs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,19 @@ public static Expression GetValueOrDefaultCall(this Expression nullableExpressio
156156

157157
[DebuggerStepThrough]
158158
public static Expression GetConversionTo(this Expression expression, Type targetType)
159-
=> (expression.Type != targetType) ? Expression.Convert(expression, targetType) : expression;
159+
{
160+
if (expression.Type == targetType)
161+
{
162+
return expression;
163+
}
164+
165+
if (expression.Type.GetNonNullableType() == targetType)
166+
{
167+
return expression.GetValueOrDefaultCall();
168+
}
169+
170+
return Expression.Convert(expression, targetType);
171+
}
160172

161173
public static Expression WithToArrayCall(this Expression enumerable, Type elementType)
162174
{

AgileMapper/Members/ExpressionInfoFinder.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,11 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCall)
151151
if ((methodCall.Object != _mappingDataObject) &&
152152
(methodCall.Method.DeclaringType != typeof(IMappingData)))
153153
{
154+
if (IsNullableGetValueOrDefaultCall(methodCall))
155+
{
156+
AddExistingNullCheck(methodCall.Object);
157+
}
158+
154159
AddStringMemberAccessSubjectIfAppropriate(methodCall.Object);
155160
AddInvocationIfNecessary(methodCall);
156161
AddMemberAccessIfAppropriate(methodCall);
@@ -159,6 +164,13 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCall)
159164
return base.VisitMethodCall(methodCall);
160165
}
161166

167+
private static bool IsNullableGetValueOrDefaultCall(MethodCallExpression methodCall)
168+
{
169+
return (methodCall.Object != null) &&
170+
(methodCall.Method.Name == "GetValueOrDefault") &&
171+
(methodCall.Object.Type.IsNullableType());
172+
}
173+
162174
private void AddExistingNullCheck(Expression checkedAccess)
163175
{
164176
_nullCheckSubjects.Add(checkedAccess.ToString());

0 commit comments

Comments
 (0)