Main Content

Create .NET Collections

This example uses two System.String arrays, d1 and d2, to create a generic collection list. It shows how to manipulate the list and access its members. To create the arrays, type:

d1 = NET.createArray('System.String',3);
d1(1) = 'Brachiosaurus';
d1(2) = 'Shunosaurus';
d1(3) = 'Allosaurus';

d2 = NET.createArray('System.String',4);
d2(1) = 'Tyrannosaurus';
d2(2) = 'Spinosaurus';
d2(3) = 'Velociraptor';
d2(4) = 'Triceratops';

Create a generic collection, dc, to contain d1. The System.Collections.Generic.List class is in the mscorlib assembly, which MATLAB® loads automatically.

dc = NET.createGeneric('System.Collections.Generic.List',{'System.String'},3)
  List<System*String> handle

    Capacity: 3
       Count: 0

The List object dc has a Capacity of three, but currently is empty (Count = 0).

Use the AddRange method to add the contents of d1 to the list. For more information, search the Web for System.Collections.Generic and select the List class.

AddRange(dc,d1);

List dc now has three items:

dc.Count

To display the contents, use the Item method and zero-based indexing:

for i = 1:dc.Count
  disp(dc.Item(i-1))
end
Brachiosaurus
Shunosaurus
Allosaurus

Another way to add values is to use the InsertRange method. Insert the d2 array starting at index 1:

InsertRange(dc,1,d2);

The size of the array has grown to seven. To display the values, type:

for i = 1:dc.Count
  disp(dc.Item(i-1))
end
Brachiosaurus
Tyrannosaurus
Spinosaurus
Velociraptor
Triceratops
Shunosaurus
Allosaurus

The first item in the d2 array ('Tyrannosaurus') is at index 1 in list dc:

System.String.Compare(d2(1),dc.Item(1))

The System.String.Compare answer, 0, indicates that the two values are equal.

Related Topics

External Websites