0

I am having an issue with initializing an array in my class. In the constructor of the class I set a hierarchy depth to be later used for initializing an array of that size. If I just use [int]$Depth = 8 everything works fine, however if I try to pass the $Depth via the constructor it is not working (Error: Cannot index into a null array). What am I doing wrong?

Part of the code:

class Hierarchy {

[int]$Depth = 8 // If I add a number here it works
[string]$Name
[string]$HideMembers

#Constructor
Hierarchy ([string] $Name, [string] $HideMembers, [int] $Depth)
{
    $this.Name = $Name
    $this.HideMembers = $HideMembers
    $this.Depth = $Depth // it seems this is executed after the creation of the $levels array
}

[Level[]]$Levels = [Level[]]::new($this.Depth)

1 Answer 1

1

I would do it like this:

class Hierarchy {

    [int]$Depth
    [string]$Name
    [string]$HideMembers
    [Level[]]$Levels

    #Constructor
    Hierarchy ([string] $Name, [string] $HideMembers, [int] $Depth)
    {
        $this.Name = $Name
        $this.HideMembers = $HideMembers
        $this.Depth = $Depth
        $this.Levels = [Level[]]::new($this.Depth)
    }

}

And then create with:

$hierarchy = New-Object Hierarchy "name", "hideMembers", 5

enter image description here

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

1 Comment

Thanks Alocin! It seems I made my life more difficult than necessary ;-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.