Skip to content

Commit 8825efb

Browse files
authored
Fix 367: generate proper expression for null-coalescing operators on nullable types (#369)
1 parent b0aeeb3 commit 8825efb

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/DynamicExpresso.Core/Parsing/Parser.cs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,16 @@ private Expression ParseConditional()
249249
{
250250
NextToken();
251251
var exprRight = ParseExpressionSegment();
252-
expr = GenerateConditional(GenerateEqual(expr, ParserConstants.NullLiteralExpression), exprRight, expr, errorPos);
252+
if (TypeUtils.IsNullableType(expr.Type))
253+
{
254+
// expr.HasValue ? expr.Value : exprRight
255+
expr = GenerateConditional(GenerateGetNullableHasValue(expr), GenerateGetNullableValue(expr), exprRight, errorPos);
256+
}
257+
else
258+
{
259+
// expr == null ? exprRight : expr
260+
expr = GenerateConditional(GenerateEqual(expr, ParserConstants.NullLiteralExpression), exprRight, expr, errorPos);
261+
}
253262
}
254263
else if (_token.id == TokenId.Question)
255264
{
@@ -734,6 +743,16 @@ private Expression ParsePrimary()
734743
return expr;
735744
}
736745

746+
/// <summary>
747+
/// Generate a call to the HasValue property of the Nullable type */
748+
/// </summary>
749+
private Expression GenerateGetNullableHasValue(Expression expr)
750+
{
751+
if (!TypeUtils.IsNullableType(expr.Type))
752+
return expr;
753+
return GeneratePropertyOrFieldExpression(expr.Type, expr, _token.pos, "HasValue");
754+
}
755+
737756
/// <summary>
738757
/// Generate a call to the Value property of the Nullable type */
739758
/// </summary>

test/DynamicExpresso.UnitTest/GithubIssues.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -891,6 +891,16 @@ public void GitHub_Issue_354()
891891

892892
Assert.That(interpreter.Eval<Guid>("b.ReturnsGuid()"), Is.EqualTo(Guid.Empty));
893893
}
894+
895+
[Test]
896+
public void GitHub_Issue_367()
897+
{
898+
var interpreter = new DynamicExpresso.Interpreter();
899+
interpreter.SetVariable("MyValue", null, typeof(int?));
900+
901+
var result = interpreter.Eval<int>("MyValue ?? 10");
902+
Assert.That(result, Is.EqualTo(10));
903+
}
894904
}
895905

896906
internal static class GithubIssuesTestExtensionsMethods

0 commit comments

Comments
 (0)