3

This is kind of a tangent to this question:

Retrieving the calling method name from within a method

public Main()
{
     PopularMethod();
}

public ButtonClick(object sender, EventArgs e)
{
     PopularMethod();
}

public Button2Click(object sender, EventArgs e)
{
     PopularMethod();
}

public void PopularMethod()
{
     //Get calling method name
}

Is it possible to use reflection to get a list of functions that call upon the "PopularMethod" function in it's body? Ie: [Main, ButtonClick, Button2Click]

Update: C# reflection and finding all references Was what I was looking for! woot! Thank you all

Community
  • 1
  • 1
mBrice1024
  • 790
  • 5
  • 25
  • Sure - static analysis tools within visual studio and other 3rd party tools can do this. Nothing built in to the framework, though. – D Stanley Jan 17 '17 at 02:09
  • @D Stanley I imagine that these tools parse the actual code and can locate declarations/usages that way. I wonder why you would want to do this programatically? – GantTheWanderer Jan 17 '17 at 02:10
  • 1
    Solution should be similar to this [one](http://stackoverflow.com/a/5490526/324260). – Ilian Jan 17 '17 at 02:30

2 Answers2

2

There is an attribute you can use to let the runtime services get this information for you:

public void PopularMethod([System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
{

}

Read more here: https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx

JuanR
  • 7,405
  • 1
  • 19
  • 30
  • 1
    Thanks for the reply Juan, but it's not quite what I'm looking for. That requires PopularMethod to have been called. I'm more looking to get a programmatic call hierarchy using just C# reflection with out having the call any methods. – mBrice1024 Jan 17 '17 at 02:21
  • I understand now. Take a look at this then: http://stackoverflow.com/questions/31861762/finding-all-references-to-a-method-with-roslyn – JuanR Jan 17 '17 at 02:46
0

Have a look at System.Diagnostics, there is StackTrace class in there which might be helpful.

StackTrace st = new StackTrace(true);
for(int i =0; i< st.FrameCount; i++ )
{
    // Note that high up the call stack, there is only
    // one stack frame.
    StackFrame sf = st.GetFrame(i);
    Console.WriteLine();
    Console.WriteLine("High up the call stack, Method: {0}",
        sf.GetMethod());

    Console.WriteLine("High up the call stack, Line Number: {0}",
        sf.GetFileLineNumber());
}
Yaser
  • 5,609
  • 1
  • 15
  • 27
  • You could use this to find all called functions which call PopularFunction. This would not find references to things that were not called, so not sure if this can provide a list of every reference. – GantTheWanderer Jan 17 '17 at 02:13