Click here to Skip to main content
12,511,896 members (47,492 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C#
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 14-Jul-10 3:55am
fadime429
Updated 14-Jul-10 4:35am
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
Comments
Nishant Sivakumar 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 !
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

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

A test class:

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:

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
  Permalink  

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160929.1 | Last Updated 23 Sep 2014
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100