Main Content

Call .NET Generic Methods

A generic method declares one or more parameterized types. For more information, search for the term generics in the documentation for a .NET class library, as described in To Learn More About .NET.

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.

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 Build 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');


The methods and methodsview functions do not list generic methods. Use the Display .NET Generic Methods Using Reflection example.

Invoke Generic Class Member Function

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

cls = NetDocGeneric.SampleClass();

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

ret = NET.invokeGenericMethod(cls,...

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(cls,'GenMethodWithMixedArgs',...

To return arg2, use the syntax:

ret = NET.invokeGenericMethod(cls,'GenMethodWithMixedArgs',...

Invoke Static Generic Functions

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

ret = NET.invokeGenericMethod('NetDocGeneric.SampleClass',...

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',...

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

ret = NET.invokeGenericMethod(genClsDef,...

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.

Related Topics