Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array and array member methods

The following PowerShell code:

class MyClass { }
class MyClass1 : MyClass {
    [void] OutMsg([string] $Str) {
        Write-Host -Object "MyClass1: $Str"
    }
}
class MyClass2 : MyClass {
    [void] OutMsg([string] $Str) {
        Write-Host -Object "MyClass2: $Str"
    }
}
[MyClass[]] $ClassArray = @([MyClass1]::new(), [MyClass2]::new())
$ClassArray.OutMsg('TestString')

outputs:

MyClass1: TestString
MyClass2: TestString

Calling

Get-Member -InputObject $ClassArray

shows me that the array object itself has no OutMsg method.

Why can I call $ClassArray.OutMsg('') though (looks like this calls the OutMsg method of each array member in turn)?

like image 992
Andreas Avatar asked May 29 '26 05:05

Andreas


1 Answers

That is actually a well defined behavior of arrays in PowerShell.

To quote the documentation:

Starting in PowerShell 3.0, when you use the member-access operator to access a member that doesn't exist on a list collection, PowerShell automatically enumerates the items in the collection and attempts to access the specified member on each item.

You can find additional details in the about member-access enumeration page.

like image 116
Mureinik Avatar answered May 31 '26 19:05

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!