Click here to Skip to main content
15,891,757 members
Please Sign up or sign in to vote.
5.00/5 (8 votes)
See more:
Hi,

I want to find the location of all method calls to a single class at runtime. I'm using reflection, but I cannot find a way to locate where it is being used. For example:

public class Test 
{
   public void Method1()
   { 
     // do something 
   }
   public void Method2()
   {
     Method2();
   }
}


I want to find at runtime Method2 is called by Method1. Is there a way?

I think there should be, as Visual Studio can do it via "Find All References". Thanks.
Posted
Updated 28-Sep-17 2:30am
v2

I am not sure if this is exactly what you want. But may be this will help you: -

A test class:

C#
public class TestClass
{
    public void Test()
    {
        Console.WriteLine("Test");
        Console.Write(10);
        DateTime date = DateTime.Now;
        Console.WriteLine(date);
    }
}



Another code to print all the methods used within TextClass.Test()

MethodBase methodBase = typeof(TestClass).GetMethod("Test");
var instructions = MethodBodyReader.GetInstructions(methodBase);

foreach (Instruction instruction in instructions)
{
    MethodInfo methodInfo = instruction.Operand as MethodInfo;

    if(methodInfo != null)
    {
        Type type = methodInfo.DeclaringType;
        ParameterInfo[] parameters = methodInfo.GetParameters();

        Console.WriteLine("{0}.{1}({2});",
            type.FullName,
            methodInfo.Name,
            String.Join(", ", parameters.Select(p => p.ParameterType.FullName + " " + p.Name).ToArray())
        );
    }
}


The output was:

MIDL
System.Console.WriteLine(System.String value);
System.Console.Write(System.Int32 value);
System.DateTime.get_Now();
System.Console.WriteLine(System.Object value);


Hope this helps. Let me know if or not this helped you.

--
AJ
 
Share this answer
 
I would imagine you'd need to parse the method body of the methods you're looking at, see this[^]. It might help you get started.

Btw, if you're doing this within a Visual Studio macro, I believe VS provides some objects that might be of use to doing this without IL parsing.
 
Share this answer
 
Comments
Nish Nishant 14-Jul-10 11:02am    
Reason for my vote of 5
Worth 5!
SKOTAJI 4-May-11 12:54pm    
Need to refer this concept. Good to post here !
Voted 5 !

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900