diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index 2b6d72ae0c..d4492f47c7 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -519,7 +519,18 @@ namespace System.Management.Automation invocationInfo: null, propagateAllExceptionsToTop: true, args: args); - Diagnostics.Assert(result.Count == 1, "Code generation ensures we return the correct type"); + + // This is needed only for the case where the + // method returns [object]. If the argument to 'return' + // is a pipeline that emits nothing then result.Count will + // be zero so we catch that and "convert" it to null. Note that + // the return statement is still required in the method, it + // just recieves nothing from it's argument. + if (result.Count == 0) + { + return default(T); + } + return (T)result[0]; } diff --git a/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 index 5185aa38b2..83617bd25e 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 @@ -116,6 +116,16 @@ Describe 'Positive Parse Properties Tests' -Tags "CI" { class C9b { [System.Collections.Generic.List[C9b]] f() { return [C9b]::new() } } $c9b = [C9b]::new().f() It "Expected a System.Collections.Generic.List[C9b] returned" { $c9b -is [System.Collections.Generic.List[C9b]] | Should -BeTrue } + It 'Methods returning object should return $null if no output was produced' { + class Foo { + [object] Bar1() { return & {} } + static [object] Bar2() { return & {} } + } + # Test instance method + [Foo]::new().Bar1() | Should -BeNullOrEmpty + # Test static method + [foo]::Bar2() | Should -BeNullOrEmpty + } } It 'Positive ParseProperty Attributes Test' {