Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get types used inside a specific class

Here's the class, which I want to get a list of all types used in it:

public class TestClass : MonoBehaviour{
    private UIManager _manager;

    private void Initialize(UIManager manager){
        _manager = manager;
    }
}

Then I thought that by running something like this:

    Assembly assembly = typeof (TestClass).Assembly;
    foreach (Type type in assembly.GetTypes()){
        Debug.Log(type.FullName);
    }

Would give me just the UIManager type. But instead it seems like it's giving me the list of all types used on my project.

How can I get just the types used on this class?

(as you can see TestClass inherits from MonoBehaviour, but I don't want the types used there, I want the types used specifically in TestClass).

like image 900
Vasco Avatar asked Feb 15 '26 23:02

Vasco


1 Answers

If you want to know what types used for methods/fileds/properties - use basic reflection to enumerate each of the methods/fields and grab types used in declaration.

I.e. for method you'd call Type.GetMethods and than dig through MethodInfo properties like MethodInfo.ReturnType to get used types. Potentially go down recursively through each base class/interface to find all dependencies.

If you want to know what types used inside methods you'll need to use some sort of IL parser as reflection does not provide way to peek into method's body. Sample can be found in Get types used inside a C# method body.

Note that there are existing tools that provide similar functionality already - i.e. ReSahrper has "find code depending on module" and "find usages for types/methods/...".

like image 170
Alexei Levenkov Avatar answered Feb 18 '26 13:02

Alexei Levenkov