Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 14 additions & 10 deletions src/System.Management.Automation/engine/parser/Compiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -982,19 +982,23 @@ private static Expression Coalesce(Expression left, Expression right)
{
return left;
}
else if (leftType == typeof(AutomationNull))
{
return right;
}
Comment thread
TravisEz13 marked this conversation as resolved.
else
{
Expression lhs = left.Cast(typeof(object));
Expression rhs = right.Cast(typeof(object));
ParameterExpression lhsStoreVar = Expression.Variable(typeof(object));
var blockParameters = new ParameterExpression[] { lhsStoreVar };
var blockStatements = new Expression[]
{
Expression.Assign(lhsStoreVar, left.Cast(typeof(object))),
Expression.Condition(
Expression.Call(CachedReflectionInfo.LanguagePrimitives_IsNull, lhsStoreVar),
right.Cast(typeof(object)),
lhsStoreVar),
};

return Expression.Condition(
Expression.Call(CachedReflectionInfo.LanguagePrimitives_IsNull, lhs),
rhs,
lhs);
return Expression.Block(
typeof(object),
blockParameters,
blockStatements);
}
}

Expand Down
12 changes: 12 additions & 0 deletions test/powershell/Language/Operators/NullConditional.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,18 @@ Describe 'NullCoalesceOperations' -Tags 'CI' {
It 'Lhs is $?' {
{$???$false} | Should -BeTrue
}

It 'Should only evaluate LHS once when it IS null' {
$testState = [pscustomobject]@{ Value = 0 }
(& { [void]$testState.Value++ }) ?? 'Nothing' | Should -BeExactly 'Nothing'
$testState.Value | Should -Be 1
}

It 'Should only evaluate LHS once when it is NOT null' {
$testState = [pscustomobject]@{ Value = 0 }
(& { 'Test'; [void]$testState.Value++ }) ?? 'Nothing' | Should -BeExactly 'Test'
$testState.Value | Should -Be 1
}
}

Context 'Null Coalesce ?? operator precedence' {
Expand Down