PowerShell - Class Attribute is second Class but not getting any values for their attributes

44 views Asked by At

I have one class with default value for Status Message:

class DeploymentState {
    [string] $StatusMessage

    DeploymentState() {
        $this.StatusMessage = "initial status."
    }    
}

I have Second Class which references the first one:

class Component {

[DeploymentState] $dstate

}
$c=[Component]::new()
$c.dstate.StatusMessage

I am not getting anything as output for this? Help - what I am missing? Even if I instantiate the class the result is the same:

$dstate=[DeploymentState]::new()
$c.dstate.StatusMessage

Thanks

1

There are 1 answers

0
Peter Schneider On

Try this

class DeploymentState {
    [string] $StatusMessage = "initial status."

    DeploymentState([string]$status) {
        $this.StatusMessage = $status
    }    

    DeploymentState() {
    }    
}

You will also need a constructor inside your Component class in which you create a new instance of your $dstate property, else it will be null, that's why there's no output.

class Component {

    [DeploymentState] $dstate

    Component() {
        $this.dstate = [DeploymentState]::new()
    }
}

Now the following gives you a result

$c=[Component]::new()
$c.dstate.StatusMessage

and this one also

$dstate=[DeploymentState]::new()
$dstate.StatusMessage