Products & Services Industries Academia Support User Community Company

Learn more about MATLAB   

Using Generic Classes

Overview

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 Calling Generic Methods.

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

Instances of the NET.GenericClass helper class are intended to be used 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 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:

System.String RetVal Item	
  (System.Collections.Generic.List<System*String> this, 
  int32 scalar index)

The syntax to use Item to set a value is:

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

Example — Creating a Collection

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

d1 = NET.createArray('System.String', 3);
d1.Set(0, 'Brachiosaurus');
d1.Set(1, 'Mamenchisaurus');
d1.Set(2, 'Amargasaurus');

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

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

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

You can see from the following information that the List object dc has a Capacity of three, but currently is empty (Count = 0).

  System.Collections.Generic.List<System*String> handle
  Package: System.Collections.Generic

  Properties:
    Capacity: 3
       Count: 0

  Methods, Events, Superclasses

MATLAB also opens a window showing the method signatures for the List class. For more information, search the Web for System.Collections.Generic and select the List class. Use the AddRange method to add the contents of d1 to the list.

dc.AddRange(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

MATLAB displays:

Brachiosaurus
Mamenchisaurus
Amargasaurus

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

dc.InsertRange(1,d2);
dc.Capacity
dc.Count

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

MATLAB displays:

Brachiosaurus
Triceratops
Tyrannosaurus
Deinonychus
Velociraptor
Mamenchisaurus
Amargasaurus

You see that the first item in the d2 array ('Triceratops') is at index 1 in list dc:

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

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

Example — Converting a 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 = dc.GetRange(2,3);
dArr = temp.ToArray;
for i=1:dArr.Length; disp(dArr.Get(i-1)); end

MATLAB displays:

Tyrannosaurus
Deinonychus
Velociraptor

To create a MATLAB array D:

D = {char(dArr.Get(0)), char(dArr.Get(1)), char(dArr.Get(2))}

MATLAB displays:

D = 
    'Tyrannosaurus'    'Deinonychus'    'Velociraptor'

The dArr array is zero-based and matrix D is one-based:

strcmp(char(dArr.Get(0)),D(1))

In this case, the strcmp answer, 1, indicates the two values are equal.

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

D'

MATLAB displays:

ans = 
    'Tyrannosaurus'
    'Deinonychus'
    'Velociraptor'

Sort the array alphabetically:

sort(D)

MATLAB displays:

ans = 
    'Deinonychus'    'Tyrannosaurus'    'Velociraptor'

Calling 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:

The NET.invokeGenericMethod function cannot invoke overloaded generic methods if they are overloaded on the argument data type. The following C# class has such methods:

class MyClass
{
    public void OverloadedGenericMethod<T>(T t, int i) { }
    public void OverloadedGenericMethod<T>(T t, double d) { }
    public void OverloadedGenericMethod<T>(int i, T t) { }
    public void OverloadedGenericMethod<T>(double d, T t) { }
}

Before You Begin

The Example C# Classes for Invoking Generic Methods define simple generic methods that illustrate the NET.invokeGenericMethod syntax. If you want to execute the MATLAB commands shown in the following examples, create an application from the DocGeneric classes. For guidelines, see the build instructions in Using netdoc.NetSample.

For example, if you create an application with the assembly name GenericExamples and put it in your c:\work directory, you can type the following MATLAB commands to load the assembly:

filePath = fullfile('c:','work','GenericExamples.dll');
NET.addAssembly(filePath);

Example C# Classes for Invoking Generic Methods

using System;
using System.Collections.Generic;
using System.Text;

namespace DocGeneric
{
    public class SampleClass
    {
        public K GenMethod<K>(K arg) 
        { 
            // set type of arg to K
            return (arg); 
        }        
        public K GenMethodWithMixedArgs<K>(K arg1, K arg2, bool tf)
        { 
            // if true, return arg1
            // if false, return arg2
            return (tf ? arg1 : arg2); 
        }
        public static K GenStaticMethod<K>(K arg) 
        { 
            return (arg); 
        }
        public static K GenStaticMethodWithMixedArgs<K>
            (K arg1, K arg2, bool tf) 
        { 
            return (tf ? arg1 : arg2); 
        }
    }

    public class SampleGenericClass<T>
    {
        public string ParameterizedGenMethod<K>(T clsParam, K arg)
        { 
            return (clsParam.GetType().Name + ", " + 
                arg.GetType().Name); 
        }
        public T GenMethod<T>(T arg) 
        { 
            return (arg); 
        }
        public static K GenStaticMethod<K>(K arg) 
        { 
            return (arg); 
        }
        public static K GenStaticMethodWithMixedArgs<K>
            (K arg1, K arg2, bool tf) 
        { 
            return (tf ? arg1 : arg2); 
        }
        public static string ParameterizedStaticGenMethod<K>
            (T clsParam, K arg) 
        { 
            return (clsParam.GetType().Name + ", " + 
                arg.GetType().Name); 
        }
    }
}

Invoke Generic Class Member Function

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

obj = DocGeneric.SampleClass();

To convert 5 to an integer parameter type like 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('DocGeneric.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('DocGeneric.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.

  


Recommended Products

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

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