4

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?

0

2 Answers 2

15

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())
Sign up to request clarification or add additional context in comments.

1 Comment

If you were here - I'd buy you a beer.
7

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!

1 Comment

No problem ;-) That snippet's interesting, it's creating a Python list with one object in it (a new Class1 object), which the List<T> constructor seems to accept as an IEnumerable to create items from. Cool!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.