MATLAB: How to use a Collection.ArrayList in the C# application and pass it to the MATLAB .NET component

arraylistbuildercforMATLABMATLAB Builder for COMnet

I want to create an Collections.ArrayList in C# and pass it to a .NET component created with MATLAB Builder for .NET.

Best Answer

You can use the ICollection.CopyTo method to make a shallow copy of the elements of the collection to a standard C# array. You can then cast this array to a MATLAB data type. Here is a simple exmple:
MATLAB code:
function ConsolePrinter(A)
disp(A)
C#-code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using MathWorks.MATLAB.NET.Arrays;
using ConsolePrinter;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//Instanciate the MATLAB component
ConsolePrinterclass Pr = new ConsolePrinterclass();
//Initialize and populate a Collections.ArrayList
ArrayList list1 = new ArrayList(5);
list1.Add("Jody");
list1.Add("Red");
list1.Add("John");
list1.Add("Xiaoyu");
list1.Add("Black");
//Create shallow copy of the ArrayList alements to an array
string[] array1 = new string[5];
list1.CopyTo(array1, 0);
//print container element to screen
foreach (string i in array1)
{
Console.WriteLine("Element as native C# array:\n" + "\t" + i);
Console.WriteLine("Element as MathWorks type from MCR:");
Pr.ConsolePrinter(new MWCellArray(i));
}
//wait for user to exit
Console.ReadLine();
}
}
}
You may need to invoke IDisposible.Dispose method to garbage collect the collection.
This method will work for any of the System.Collections objects i.e. deque, queue, stack...