1

I'm trying to make a simple blackjack game as a Powershell script and found out that my ArrayList is not behaving as expected. I want to understand why I get a different answer then expected.

The Write-Host $deck call inside the function prints out the deck as I expect, 52 objects. So far so good.

However, when calling Write-Host $myDeck the weird part begins. What it will do is, it will first print 0...51 and then my actual deck. So instead of having 52 objects in my ArrayList I get 104 (52+52). Can anyone explain what really happens here? Because I find this super confusing.

function Get-Deck(){

    $ranks = 2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"
    $suits = "Spade","Heart","Diamond","Club"
    $deck = [System.Collections.ArrayList]::new()

    foreach($rank in $ranks){
        foreach($suit in $suits){
            $card = $rank , $suit
            $deck.Add($card)
        }
    }

    Write-Host $deck #prints out the actual array with 52 cards. 
    return $deck

}

$myDeck = Get-Deck
Write-Host $myDeck #prints out: 0 1 2 3 4 5 6 7 ... 51 2 Spade 2 Heart 2 Diamond ... Ace Club

1 Answers1

4

The unexpected ouptut is caused by ArrayList.Add(). The function prototype is like so,

public virtual int Add (object value);

Note that it's got a non-void return type, int which is the ArrayList index at which the value has been added.

When $deck.Add($card) is called, the return value is left lingering on the pipeline and ends up in the arraylist. To fix the issue, either assigning the return value into an explicit variable, pass to null or cast as void. There are a few gotchas, see another an answer about those. Any of these should work. Like so,

$null = $deck.Add($card) # Preferred, (ab)uses automatic variable
[void]$deck.Add($card) # Works too
$deck.Add($card) | out-null # Works, but is the slowest option
$foo = $deck.Add($card) # Use this if you need the index value
vonPryz
  • 22,996
  • 7
  • 54
  • 65
  • Nice, though it's worth mentioning `$null = $deck.Add($card)` for output suppression - it's syntactically easy (unlike `[void]`, which may require `(...)`) and fast (unlike `Out-Null` or `>$null`) - [this answer](https://stackoverflow.com/a/55665963/45375) discusses output-suppression options in detail. – mklement0 Oct 29 '19 at 13:01