How to test if an object is any type of array or list?

75 Views Asked by At

I want to test if an object is a string or any type of array or list (not hashtable or dictionary, etc.) It seems impossible to test for every type of collection in .NET. I must be missing some ICollection type.

I have tried something like:

($list -is [Collections.IEnumerable]) -and ($list -isnot [Collections.IDictionary])

But a stack or queue would return true in that test.

1

There are 1 best solutions below

1
On BEST ANSWER

Technically a hashtable and other Dictionary types are Collections. Queue and Stack are also Collections, they implement the ICollection interafce.

The interface you could target in this case, if I understood correctly what you're looking for, is IList. array, ArrayList, List<T> and other collection types have this interface in common:

$instancesToTest = (
    @(),
    @{},
    [ordered]@{},
    [System.Collections.ObjectModel.Collection[string]]::new(),
    [System.Management.Automation.PSDataCollection[string]]::new(),
    [System.Collections.Generic.List[string]]::new(),
    [System.Collections.Generic.Dictionary[string, string]]::new(),
    [System.Collections.Generic.Queue[string]]::new(),
    [System.Collections.Generic.Stack[string]]::new(),
    [System.Collections.Stack]::new(),
    [System.Collections.Queue]::new(),
    [System.Collections.ArrayList]::new()
)

$instancesToTest | ForEach-Object {
    [pscustomobject]@{
        Type    = $_.GetType()
        IsIList = $_ -is [System.Collections.IList]
    }
} | Sort-Object IsIList -Descending

There is also a great module you can use called ClassExplorer to find all types implementing this interface:

Find-Type -ImplementsInterface System.Collections.IList