Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# code listing all methods called from a starting method?

Tags:

methods

c#

Let's say we have methodA() that calls methodB() and methodC().

In methodB(), we call methodB1() and methodB2().

In methodC(), we call methodC1(), methodC2() and methodC3().

So at the end we have the method tree

methodA

methodB

methodB1

methodB2

methodC

methodC1

methodC2

methodC3

Is it possible to have this list via C# code?

like image 766
Nam G VU Avatar asked Nov 11 '13 06:11

Nam G VU


1 Answers

The first thing that comes to our mind when we think about determining the call flow is to check the call stack. But checking stack frames can only give us the current call hierarchy and not the previous one. i.e Even if you check stackframes in C3, it wont have the history of A calling B. So this wont work.

This means that each called method also somehow needs to participate in achieving this goal. Each method has to somehow determine that the caller is wanting to track the flow and has to contribute towards providing the required information. But adding some code in each possible method that can be called is just ridiculous.

Another way of doing this is to delegate this to someone who can intercept each method invocation, check if caller is wanting to track the flow and log the required information which can be accessed later. This is exactly where i think Aspect Oriented Programming (AOP) comes into the picture. To use AOP in .Net please have a look at PostSharp. If i get time i will try and come up with some code sample but for now i can only point you to this url: http://www.postsharp.net

I hope this helps.

like image 54
Vinod Kumar Y S Avatar answered Oct 06 '22 17:10

Vinod Kumar Y S