Skip to content

Commit 916ef56

Browse files
Staffan Gustafssonlzybkr
authored andcommitted
Call to CodeMethod returning void should work (PowerShell#4850)
Fixes PowerShell#4826
1 parent e71d003 commit 916ef56

File tree

2 files changed

+43
-3
lines changed

2 files changed

+43
-3
lines changed

src/System.Management.Automation/engine/runtime/Binding/Binders.cs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6568,9 +6568,16 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target,
65686568
var codeMethod = methodInfo as PSCodeMethod;
65696569
if (codeMethod != null)
65706570
{
6571-
return new DynamicMetaObject(
6572-
InvokeMethod(codeMethod.CodeReference, null, args.Prepend(target).ToArray(), false, MethodInvocationType.Ordinary)
6573-
.Cast(typeof(object)), restrictions).WriteToDebugLog(this);
6571+
Expression expr = InvokeMethod(codeMethod.CodeReference, null, args.Prepend(target).ToArray(), false, MethodInvocationType.Ordinary);
6572+
if (codeMethod.CodeReference.ReturnType == typeof(void))
6573+
{
6574+
expr = Expression.Block(expr, ExpressionCache.AutomationNullConstant);
6575+
}
6576+
else
6577+
{
6578+
expr = expr.Cast(typeof(object));
6579+
}
6580+
return new DynamicMetaObject(expr, restrictions).WriteToDebugLog(this);
65746581
}
65756582

65766583
var parameterizedProperty = methodInfo as PSParameterizedProperty;

test/powershell/engine/ETS/Adapter.Tests.ps1

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,39 @@ Describe "Adapter Tests" -tags "CI" {
7979
$val = $doc.ToString()
8080
$val | Should Be "book"
8181
}
82+
83+
It "Calls CodeMethod with void result" {
84+
85+
class TestCodeMethodInvokationWithVoidReturn {
86+
[int] $CallCounter
87+
88+
static [int] IntMethodCM([PSObject] $self) {
89+
return $self.CallCounter
90+
}
91+
92+
static [void] VoidMethodCM([PSObject] $self) {
93+
$self.CallCounter++
94+
}
95+
96+
static [Reflection.MethodInfo] GetMethodInfo([string] $name) {
97+
return [TestCodeMethodInvokationWithVoidReturn].GetMethod($name)
98+
}
99+
}
100+
101+
Update-TypeData -Force -TypeName TestCodeMethodInvokationWithVoidReturn -MemberType CodeMethod -MemberName IntMethod -Value ([TestCodeMethodInvokationWithVoidReturn]::GetMethodInfo('IntMethodCM'))
102+
Update-TypeData -Force -TypeName TestCodeMethodInvokationWithVoidReturn -MemberType CodeMethod -MemberName VoidMethod -Value ([TestCodeMethodInvokationWithVoidReturn]::GetMethodInfo('VoidMethodCM'))
103+
try {
104+
$o = [TestCodeMethodInvokationWithVoidReturn]::new()
105+
$o.CallCounter | Should Be 0
106+
$o.VoidMethod()
107+
$o.CallCounter | Should be 1
108+
109+
$o.IntMethod() | Should be 1
110+
}
111+
finally {
112+
Remove-TypeData TestCodeMethodInvokationWithVoidReturn
113+
}
114+
}
82115
}
83116

84117
Describe "Adapter XML Tests" -tags "CI" {

0 commit comments

Comments
 (0)