How to instantiate PrivateType of nested class

The PrivateType class is very handy when it comes to run unit tests on methods that are either private, either in an internal class.

The constructor signature is:


public PrivateType(
	string assemblyName,
	string typeName
)

You use it this way:


PrivateType t = new PrivateType("Myassembly", "Myassembly.MyNamespaces.MyInternalClass");

MyType result = t.InvokeStatic("MyMethod") as MyType ; // MyType  can be any object type

But when you are in the specific case of testing a method from an nested class of an internal class, there is a little trick

The TypeName argument of the PrivateType’s constructor is not (as we could imagine) “Myassembly.MyNamespaces.MyInternalClass.MyInnerClass” but “Myassembly.MyNamespaces.MyInternalClass+MyInnerClass” (notice the “+”)

So :


PrivateType t = new PrivateType("Myassembly", "Myassembly.MyNamespaces.MyInternalClass+MyInnerClass");

MyType result = t.InvokeStatic("MyMethod") as MyType ; // MyType  can be any object type

Help found thanks to :https://stackoverflow.com/questions/3200875/how-to-instantiate-privatetype-of-inner-private-class/22700890#22700890

Incoming search terms:

  • Nested Leave a Reply comment -captcha
  • privatetype private class
  • unity instantiate nested class