Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the result of a function call with/without parentheses

Why is there a difference in the return values of F and G in the following code?

Function F {
    Return (New-Object Collections.Generic.LinkedList[Object])
}

Function G {
    Return New-Object Collections.Generic.LinkedList[Object]
}

Function Write-Type($x) {
    If($null -eq $x) {
        Write-Host "null"
    } Else {
        Write-Host $x.GetType()
    }
}

Write-Type (F) # -> null
Write-Type (G) # -> System.Collections.Generic.LinkedList`1[System.Object]

As far as I understand, if a function returns some kind of empty collection, PowerShell will "unwrap" it into null, and so F does what I expect. But what's going on with G?

Edit: As pointed out by JPBlanc, only PowerShell 3.0 exhibits this difference. In 2.0, both lines print null. What changed?

like image 353
ahihi Avatar asked Oct 22 '22 05:10

ahihi


1 Answers

Sorry I don't read correctly your question, as F is afunction you are using () to evaluate the function. So then the result of Write-Type function is the same for me in PowerShell V2.0.

So, In PowerShell 3.0 I meet your problem.

Now using :

Trace-Command -name TypeConversion -Expression {Write-Type (F)} -PSHost

Versus

Trace-Command -name TypeConversion -Expression {Write-Type (G)} -PSHost

as far as I understand the () before before returning object generate the following

 Converting "Collections.Generic.LinkedList" to "System.Type".
     Conversion to System.Type
         Conversion to System.Type
             Could not find a match for "System.Collections.Generic.LinkedList".
         Could not find a match for "Collections.Generic.LinkedList".
 Converting "Collections.Generic.LinkedList`1" to "System.Type".
     Conversion to System.Type
         Conversion to System.Type
             Found "System.Collections.Generic.LinkedList`1[T]" in the loaded assemblies.
 Converting "Object" to "System.Type".
     Conversion to System.Type
         Conversion to System.Type
             Found "System.Object" in the loaded assemblies.
like image 115
JPBlanc Avatar answered Nov 03 '22 19:11

JPBlanc