Main Content

Display .NET Generic Methods Using Reflection

MATLAB® does not list generic methods with methods or methodsview. This showGenericMethods function uses reflection to display generic methods for a .NET object or class.

showGenericMethods MATLAB Function

function showGenericMethods(input)
% Input is a .NET Object
if isa(input, "System.Object")
    type = input.GetType();
% Input is a type name
elseif ischar(input) || isstring(input)
    type = findType(input);
% Input is unsupported
else
    disp("Unsupported input");
    return;
end
% Could not find the type
if isempty(type)
    disp(strcat(input, " not found"));
    return;
end
% Iterate through all the methods
methods = type.GetMethods();
for i=1:methods.Length
    if methods(i).IsGenericMethod
        % Display generic methods
        disp(methods(i).ToString());
    end
end
end

function type = findType(input)
% Use a simple API to search for the type
type = System.Type.GetType(input);
if ~isempty(type)
    return;
end
% Manually iterate through all loaded assemblies
assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
for i=1:assemblies.Length
    type = assemblies(i).GetType(input);
    if ~isempty(type)
        return;
    end
end
end

Display Generic Methods

These examples use SampleClass and SampleGenericClass. To see the C# code defining these classes, see C# NetDocGeneric.cs File.

For a regular class:

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

For a generic class:

mlClass = NET.createGeneric("NetDocGeneric.SampleGenericClass",{"System.Double"});
showGenericMethods(mlClass)
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)'

See Also

Topics