Interest fact about PowerShell HashSet

After banging my head on the wall trying to figure out why my dominoes exercise wasn’t working, I discovered an interesting fact about HashSet. Adding or removing elements from a HashSet returns a boolean indicating if the element was found and successfully added/removed. If the return value of Add or Remove method is not assigned to a variable or put in some control flow statement, the return value is added to whatever value the function is returning. I had a function that was returning a boolean value, and I noticed that it was returning an array of boolean values. I ended up having to do something like this:

$_dummy = $visited.Add($value)
...
$_dummy = $visited.Remove($value)

I’m sharing this tip in case it is useful for others on this track.

2 Likes

For more idiomatic ways you can cast [void] before it, or pipe it into Out-Null

2 Likes

Thanks, @glaxxie , I changed my solution to use the [void] cast, and that worked.

In PowerShell, any value returned by an expression that isn’t consumed is placed into the “Success” stream. What you describe isn’t limited to any particular instance such as the Add or Remove methods of the .Net HashSet class.