5

if I have

class A { public void DoStuff() { B b; } } struct B {} struct C {} 

and I have typeof(A),

I would like to get a list of all types used by A. in this case it would be typeof(B) and not typeof(C).

Is there a nice way to do this with reflection?

3
  • 2
    It's pretty easy to get all types of the members of A via Type.GetFields, Type.GetProperties (or Type.GetMembers) and so on. But figuring out what types are used locally within a method? Not so sure. Commented Jul 31, 2012 at 11:34
  • Do you need this at runtime? Do you have access to the code, or do you just have the Type? Commented Jul 31, 2012 at 11:37
  • Similar SO Ques: stackoverflow.com/questions/1975702/… Commented Jul 31, 2012 at 11:40

1 Answer 1

8

You need to look at the MethodBody class (there's a very good example of it's use in the link). This will let you write code like:

MethodInfo mi = typeof(A).GetMethod("DoStuff"); MethodBody mb = mi.GetMethodBody(); foreach (LocalVariableInfo lvi in mb.LocalVariables) { if (lvi.LocalType == typeof(B)) Console.WriteLine("It uses a B!"); if (lvi.LocalType == typeof(C)) Console.WriteLine("It uses a C!"); } 
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry if it was not clear from the post. I don't want to have to know the fact that B and C exist. if A also uses D, I'd like to find that out as well.
As you can see in my code, mb.LocalVariables returns a list of all the types the method uses. That should be exactly what you need to discover if it uses B, C, D or even Z.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.