Reputation: 1091
I'm new to the .Net World and Powershell. I have the following code:
$e = "A","A","A","B","A","B","A","A"
write-output $e.Replace("B", "C")
it works and prints
A
A
A
C
A
C
A
A
But I cannot find a Replace Method for system.array only for system.string. Why is it working?
Upvotes: 1
Views: 172
Reputation: 200283
The replacement is working because you're running PowerShell v3 or newer. In PowerShell v3 Microsoft added a feature called member enumeration, which makes PowerShell invoke a method or property on all elements of an array if the array object itself doesn't have such a method or property.
If you run PowerShell v2 (e.g. by invoking powershell.exe -version 2
) and run your code in that instance you'll get the following error:
Replace : Method invocation failed because [System.Object[]] doesn't contain a method named 'Replace'. At line:1 char:24 + write-output $e.Replace <<<< ("B", "C") + CategoryInfo : InvalidOperation: (Replace:String) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound
Upvotes: 3
Reputation: 1283
First of all, you don't need the "Write-Output"-part. But it works because you replace strings within the array for other strings.
Let me demonstrate:
$e = "A","A","A","B","A","B","A","A"
foreach($obj in $e){
$obj.GetType()
}
This outputs (only posted first 2 lines):
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
True True String System.Object
Upvotes: 0