Initialize C# List<T> from IronPython?
Solution 1
Made a mistake on the Class2() -- that's what I get for making an example instead of posting real code!!!
For what it's worth - I was able to initialize the List with actual instances like this:
from System.Collections.Generic import List
bar.ClassOnes = List[Class1]([Class1(Foo="bar")])
Thanks much Cameron!
Solution 2
You have a couple issues here. First, you're setting bar
to the class object Class2
(classes are first-class objects in Python).
You meant to create an instance, like this (with parentheses):
bar = Class2()
To create a List<T>
in IronPython, you can do:
from System.Collections.Generic import List
# Generic types in IronPython are supported with array-subscript syntax
bar.ClassOnes = List[Class1]()
bar.ClassOnes.Add(Class1())
Chad Brockman
Updated on June 05, 2022Comments
-
Chad Brockman about 2 years
I have a relatively deep object tree in C# that needs to be initialized from IronPython.
I'm new to python and I'm struggling with the initialization of arrays.
So as an example - say I have these classes in C#
public class Class1 { public string Foo {get;set;} } public class Class2 { List<Class1> ClassOnes {get;set;} }
I can initialize the array in Class2 like so:
var class2 = new Class2( ClassOnes = new List<Class1>() { new Class1(Foo="bar") });
In IronPython - I was trying this:
bar = Class2 bar.ClassOnes = Class1[Class1(Foo="bar")]
But I always get this message:
expected Array[Type], got Class1
Any ideas?