3

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)?

0

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.