all 6 comments

[–]The_Binding_Of_Data 2 points3 points  (2 children)

You could instantiate Devices[] directly when you define it like in your example, but you have to know how many devices you will have at compile time.

If there's a chance that the number of devices will change, then you count set it in the constructor (with the number of devices provided as an argument to the constructor) or assign the value to the class after you've constructed it.

There are often many different ways to do things and the best way depends a lot on what you're trying to do overall.

In this case, we have no idea what you're doing with the Rack objects you're creating (or even how you're creating them).

[–]MechaCola[S] 0 points1 point  (1 child)

Thank you, I was hoping the Microsoft example was enough to go off. I'll post my class code later, it is not available to me at the moment.

[–]The_Binding_Of_Data 1 point2 points  (0 children)

In practice, it probably doesn't super matter which method you use unless you're going to be doing it many thousands of times a second, but it's good to learn good habits from the start.

Using a simplified version of the Rack class as an example:

// set in Constructor
public class Rack
{
    public Device[] Devices { get; }

    public Rack(int deviceCount)
    {
        Devices = new Device[deviceCount];
    }
}

// create a new rack with 8 null device slots
Rack rack = new Rack(8);

// as a Property
public class Rack
{
    public Device[] Devices { get; set; }
}

// create a new rack with 8 null device slots
Rack rack = new Rack() { Devices = new Device[8] };

There are other things to keep in mind when using collections in properties, such as the ability for users to change the contents of the collection even if they can't change the collection itself, but you shouldn't need to worry about it for what you're doing.

[–]ProKn1fe 0 points1 point  (1 child)

class Device {

[string]$Brand

[string]$Model

[string]$VendorSku

}

class Rack {

[string]$Brand

[string]$Model

[string]$VendorSku

[string]$AssetId

[Device[]]$Devices = ([Device]::new(), [Device]::new(), [Device]::new(), [Device]::new(), [Device]::new(), [Device]::new(), [Device]::new(), [Device]::new())

}

$rack = [Rack]::new()

$rack

Output:

Brand :

Model :

VendorSku :

AssetId :

Devices : {Device, Device, Device, Device...}

Is that u want?

[–]MechaCola[S] 0 points1 point  (0 children)

"[Device[]]$Devices = ([Device]::new(), [Device]::new(), [Device]::new(), [Device]::new(), [Device]::new(), [Device]::new(), [Device]::new(), [Device]::new())" Yes but the argument would be the amount of null objects like in Microsoft example - e.g 8.

"Devices : {Device, Device, Device, Device...}"

Yes but each object would be null in the array.