Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I call GetType() on an empty array but not when its returned from a function

Tags:

powershell

In my never-ending quest to understand Powershell better can someone please explain this behaviour to me:

function fn1{return @()}
(@()).GetType()           #does not throw an error
(fn1).GetType()           #throws error "You cannot call a method on a null-valued expression."

Why does returning a value from a function make it "different"?

Interestingly (or perhaps not), piping to get-member exhibits the same behaviour in both cases:

function fn1{return @()}
@()   | gm           #does throw an error "You cannot call a method on a null-valued expression."
fn1   | gm           #does throw an error "You cannot call a method on a null-valued expression."

Colour me confused. Can someone explain this?

like image 233
jamiet Avatar asked Sep 30 '22 06:09

jamiet


1 Answers

This happens because when you return an array (and probably any other collection) from function, PowerShell will put each element of array into a pipeline. So GetType() is actually not being called on empty array, but it's elements (that are missing).

The soulution could be to return your array in another array :).

function fn1{return ,@()}
(fn1).GetType() 

Now Powershell will pass into a pipeline elements of this "parent" array, which happens to containt only one element: your empty array. Please note that you can't achieve that by return @(@()), because external @() only assures that result returned will be an array, which it already is.

like image 59
AdamL Avatar answered Oct 03 '22 03:10

AdamL