Skip to Main Content Skip to Search
Product Documentation

.NET Generic Classes in MATLAB

.NET Generic Classes

Generics are classes and methods that have placeholders (type parameters or parameterized types) for one or more types. This lets you design classes that take in a generic type and determine the actual type at run time. A common use for generic classes is to work with collections. For information about generic methods, see Call .NET Generic Methods.

The NET.createGeneric function creates an instance of the specialized generic class given the following:

Use instances of the NET.GenericClass helper class in NET.createGeneric function's parameter type list when specialization requires another parameterized class definition. The class instances serve as parameterized data type definitions and are constructed using fully qualified generic type name and a variable length list of fully qualified type names for generic type specialization. This list can also contain instances of NET.GenericClass if an extra nested level of parameterization is required.

Accessing Items in a .NET Collection

Use the Item property of the System.Collections.Generic List class to get or set an element at a specified index. Since Item is a property that takes arguments, MATLAB maps it to a pair of methods to get and set the value. For example, the syntax to use Item to get a value is:

Return TypeNameArguments
System.String RetValItem(System.Collections.Generic.
List<System*String> this,
int32 scalar index)

The syntax to use Item to set a value is:

Return TypeNameArguments
noneItem(System.Collections.Generic.
List<System*String> this,
int32 scalar index,
System.String value)

Create a .NET Collection

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)
  System.Collections.Generic.List<System*String> handle
  Package: System.Collections.Generic

  Properties:
    Capacity: 3
       Count: 0

  Methods, Events, Superclasses

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 the two values are equal.

Convert a .NET Collection to a MATLAB Array

Use the ToArray method of the System.Collections.Generic.List class to convert a collection to an array. For example, use GetRange to get three values from the list, starting with index 2. Then call ToArray to create a System.String array dArr, and display the results:

temp = GetRange(dc,2,3);
dArr = ToArray(temp);
for i=1:dArr.Length; disp(dArr(i)); end
Spinosaurus
Velociraptor
Triceratops

To create a MATLAB array D:

D = {char(dArr(1)),char(dArr(2)),char(dArr(3))}
D = 
    'Spinosaurus'    'Velociraptor'    'Triceratops'

Now you can use D in MATLAB functions. For example, if you type:

D'
ans = 
    'Spinosaurus'
    'Velociraptor'
    'Triceratops'

Sort the array alphabetically:

sort(D)
ans = 
    'Spinosaurus'    'Triceratops'    'Velociraptor'

Create .NET Array of Generic Type

This example creates a .NET array of List<Int32> generic type.

genType = NET.GenericClass('System.Collections.Generic.List',...
  'System.Int32'); 
arr = NET.createArray(genType, 5)
arr = 

  System.Collections.Generic.List<System*Int32>[] handle 
  Package: System.Collections.Generic 

  Properties: 
            Length: 5 
        LongLength: 5 
              Rank: 1 
          SyncRoot: [1x1 System.Collections.Generic.List<System*Int32>[]] 
        IsReadOnly: 0 
       IsFixedSize: 1 
    IsSynchronized: 0 

  Methods, Events, Superclasses 

Call .NET Generic Methods

A generic method declares one or more parameterized types. For more information, search for the term generics in the .NET Framework Class Library, as described in To Learn More About the .NET Framework.

Use the NET.invokeGenericMethod function to call a generic method. How you use the NET.invokeGenericMethod depends if the method is static or if it is a member of a generic class, as described in the following topics:

Using the NetDocGeneric Example

The C# example NetDocGeneric.cs, in the matlabroot/extern/examples/NET/NetSample folder, defines simple generic methods to illustrate the NET.invokeGenericMethod syntax. To see the code, open the file in MATLAB Editor. Build the NetDocGeneric assembly as described in Building a .NET Application for MATLAB Examples.

If you created the assembly NetDocGeneric and put it in your c:\work folder, type the following MATLAB commands to load the assembly:

dllPath = fullfile('c:','work','NetDocGeneric.dll');
NET.addAssembly(dllPath);

Invoke Generic Class Member Function

The GenMethod method in NetDocGeneric.SampleClass returns the input argument as type K. To call GenMethod, create an object, obj:

obj = NetDocGeneric.SampleClass();

To convert 5 to an integer parameter type, such as System.Int32, call NET.invokeGenericMethod with the object:

ret = NET.invokeGenericMethod(obj,...
    'GenMethod',...
    {'System.Int32'},...
    5);

The GenMethodWithMixedArgs method has parameterized typed arguments, arg1 and arg2, and a strongly typed argument, tf, of type bool. The tf flag controls which argument GenMethodWithMixedArgs returns. To return arg1, use the syntax:

ret = NET.invokeGenericMethod(obj,'GenMethodWithMixedArgs',...
    {'System.Double'},5,6,true);

To return arg2, use the syntax:

ret = NET.invokeGenericMethod(obj,'GenMethodWithMixedArgs',...
    {'System.Double'},5,6,false);

Invoke Static Generic Functions

To invoke static method GenStaticMethod, call NET.invokeGenericMethod with the fully qualified class name:

ret = NET.invokeGenericMethod('NetDocGeneric.SampleClass',...
    'GenStaticMethod',...
    {'System.Int32'},...
    5);

Invoke Static Generic Functions of a Generic Class

If a static function is a member of a generic class, create a class definition using the NET.GenericClass constructor:

genClsDef = NET.GenericClass('NetDocGeneric.SampleGenericClass',...
    'System.Double');

To invoke static method GenStaticMethod of SampleGenericClass, call NET.invokeGenericMethod with the class definition:

ret = NET.invokeGenericMethod(genClsDef,...
    'GenStaticMethod',...
    {'System.Int32'},...
    5);

Invoke Generic Functions of a Generic Class

If a generic method uses the same parameterized type as the generic class, you can call the function directly on the class object. If the generic uses a different type than the class, use the NET.invokeGenericMethod function.

Display .NET Generic Methods Using Reflection

showGenericMethods Function

The showGenericMethods function, reads a .NET object or a fully qualified class name and returns a cell array of the names of the generic method in the given class or object. Create the following MATLAB functions:

function output = showGenericMethods(input)
%if input is a .NET object, get MethodInfo[]
if IsNetObject(input)
    methods = GetType.GetMethods(input);
    %if input is a string, get the type and get get MethodInfo[]
elseif ischar(input) && ~isempty(input)
    type = getType(input);
    if isempty(type)
        disp(strcat(input,' not found'))
        return
    end
    methods = GetMethods(type);
else
    return;
end
%generate generic method names from MethodInfo[]
output = populateGenericMethods(methods);

end
function output = populateGenericMethods(methods)
%generate generic method names from MethodInfo[]
index = 1;
for i = 1:methods.Length
    method = methods(i);
    if method.IsGenericMethod
        output{index,1} = method.ToString.char;
        index = index + 1;
    end
end
end
function result = IsNetObject(input)
%must be sub class of System.Object to be a .NET object
result = isa(input,'System.Object');
end
function outputType = getType(input)
%input is a string representing the class name
%First try the static GetType method of Type handle.
%This method can find any type from 
%System or mscorlib assemblies
outputType = System.Type.GetType(input,false,false);
if isempty(outputType)
    %Framework's method to get the type failed.
	   %Manually look for it in
    %each assembly visible to MATLAB
    assemblies = System.AppDomain.CurrentDomain.GetAssemblies;
    for i= 1:assemblies.Length
        asm = assemblies.Get(i-1);
        %look for a particular type in the assembly
        outputType = GetType(asm,input,false,false);
        if ~isempty(outputType)
            %found the type - done
            break
        end
    end
end
end

Display Generic Methods in a Class

The NetDocGeneric assembly contains a class with generic methods.

dllPath = fullfile('c:','work','NetDocGeneric.dll');
asm = NET.addAssembly(dllPath);
asm.Classes
ans = 
    'NetDocGeneric.SampleClass'

Display the methods in SampleClass:

showGenericMethods('NetDocGeneric.SampleClass')
ans = 
    'K GenMethod[K](K)'
    'K GenMethodWithMixedArgs[K](K, K, Boolean)'
    'K GenStaticMethod[K](K)'
    'K GenStaticMethodWithMixedArgs[K](K, K, Boolean)'

Display Generic Methods in a Generic Class

The NetDocGeneric assembly contains a generic class with generic methods.

dllPath = fullfile('c:','work','NetDocGeneric.dll');
asm = NET.addAssembly(dllPath);
asm.GenericTypes
ans = 
    'NetDocGeneric.SampleGenericClass`1[T]'

Display the methods in SampleGenericClass:

obj = NET.createGeneric('NetDocGeneric.SampleGenericClass',...
          {'System.Double'});
showGenericMethods(obj)
ans = 
    'System.String ParameterizedGenMethod[K](Double, K)'
    'T GenMethod[T](T)'
    'K GenStaticMethod[K](K)'
    'K GenStaticMethodWithMixedArgs[K](K, K, Boolean)'
    'System.String ParameterizedStaticGenMethod[K](Double, K)'
  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS