Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using New-Object -Property to set properties of a nested class

Lets say I define the following classes in C# inside a powershell script:

Add-Type -TypeDefinition @"
public class InnerClass {
    int a, b;
    public int A { get { return a; } set { a = value; } }
    public int B { get { return b; } set { b = value; } }
}
public class SomeClass {
    string name;
    public string Name { get { return name; } set { name= value; } }
    InnerClass numbers;
    public InnerClass Numbers { get { return numbers; } set { numbers = value; } }
}
"@

I can instantiate an instance of InnerClass like so:

New-Object InnerClass -Property  @{
    'A' = 1;
    'B' = 2;
}

However, if I want to instantiate SomeClass and set the properties for InnerClass in a similar manner, it fails.

New-Object SomeClass -Property @{
    'Name' = "Justin Dearing";
    Numbers = @{
        'A' = 1;
        'B' = 2;
    };
} ;

New-Object : The value supplied is not valid, or the property is read-only. Cha
nge the value, and then try again.
At line:20 char:11
+ New-Object <<<<  SomeClass -Property @{
    + CategoryInfo          : InvalidData: (:) [New-Object], Exception
    + FullyQualifiedErrorId : InvalidValue,Microsoft.PowerShell.Commands.NewOb 
   jectCommand



Name    : Justin Dearing
Numbers : 

Is there anyway to set SomeClass, including the properties of Numbers in one New-Object statement?

like image 470
Justin Dearing Avatar asked Feb 24 '23 01:02

Justin Dearing


1 Answers

You can't directly but you can have the innerclass constructed inline with

New-Object SomeClass -Property @{
'Name' = "Justin Dearing";
'Numbers' = New-Object InnerClass -Property  @{
  'A' = 1;
  'B' = 2;
 }  
};
like image 141
klumsy Avatar answered Mar 15 '23 13:03

klumsy