Main Content

Use .NET Nested Classes

In MATLAB®, you cannot directly instantiate a nested class but here is how to do it through reflection. The following C# code defines InnerClass nested in OuterClass:

namespace MyClassLibrary
{
  public class OuterClass
  {
      public class InnerClass
      {
          public String strmethod(String x)
          {
              return "from InnerClass " + x;
          }
       }
   }
}

If the MyClassLibrary assembly is in your c:\work folder, load the file:

a = NET.addAssembly('C:\Work\MyClassLibrary.dll');
a.Classes
ans = 
    'MyClassLibrary.OuterClass'
    'MyClassLibrary.OuterClass+InnerClass'

To call strmethod, type:

t = a.AssemblyHandle.GetType('MyClassLibrary.OuterClass+InnerClass');
sa = System.Activator.CreateInstance(t);
strmethod(sa,'hello')
ans = 
from InnerClass hello