Freigeben über


Traversing elements in an IEnumerable from X++

This issue recently came up: How do you traverse the elements in an instance of an IEnumerable<T> from X++?

The answer is not as simple as it should be. The problem is that the X++ language does not currently support generics as a firstclass part of the managed X++ story. This means that we need to do some tricks to make this work. At least it shows off the capabilities of the ClrObject class: It can take a string that designates the type that you want to create an instance of. The CLR runtime system is so cleverly designed that it allows decorating types so they designate generic types. This is done by appending the backtick character, followed by the number of generic arguments, enclosed by the argument types enclosed in angular brackets.

So, the type

System.Collections.Generic.List<int> 

is  represented as

System.Collections.Generoc.List`1[System.Int]

With this knowledge the task is not hard:

 

 static void GenericTypeDemo(Args _args) 
{ 
    ClrObject o = new ClrObject("System.Collections.Generic.List`1[System.Int32]"); 
    ClrObject enumerator; 
    int theValue; 
 
    // o is an instance of an IEnumerable<int> 
    o.Add(1); 
    o.Add(4); 
    o.Add(12); 
 
    print o.ToString(); 
 
    enumerator = o.GetEnumerator(); 
 
    while (enumerator.MoveNext()) 
    { 
        theValue = enumerator.get_Current(); 
        print theValue; 
    } 
 
    pause; 
}

Comments

  • Anonymous
    January 20, 2010
    Interesting! I just figured out that I can only send these types back to Business Connector code (see remarks section): http://msdn.microsoft.com/en-us/library/microsoft.dynamics.businessconnectornet.axaptaobject.aspx I struggled for day trying to send my own custom .Net types, but all I got was weird errors. .Net in X++ is still hard. I hope they improve the .Net experience in X++ with next version of Dynamics AX.

  • Anonymous
    February 15, 2012
    Hi, how do i pass IEnumerable object from X++ in to my C# method ? Thanks, San

  • Anonymous
    August 06, 2013
    Thank you for this post! It helped me resolve my issue with mapping C# types to X++ types.