Visual Studio - Discover if method is called by another method at some point

123 views Asked by At

I was wondering, does visual studio have a feature such that I gave it a 2 method names and it then works out if at somewhere along the call stack the first method is called by the second (statically, without having to debug).

e.g. Say I have a method FireBullet, and I want to see if IsOutsideWestBoundary can be invoked at some point

FireBullet()->HitTest()->CheckBoundaries()->IsOutsiteWestBoundary()

You can see that FireBullet can eventually cause IsOutsideWestBoundary to be invoked at some point.

I understand this can potentially become a very large problem, especially with deep call stacks and multiple methods called at each level, but still, for relatively small call stacks depths, this could be very useful.

Surely something like this must exist?

Thanks Thomas

1

There are 1 answers

0
Patrick from NDepend team On

The Visual Studio extension NDepend can do that. It lets write code rules and code queries through C# LINQ queries. The following LINQ code query, executed live in Visual Studio, answers your need:

from m in Methods 
where m.Name == "FireBullet()"
let depth0 = m.DepthOfIsUsing("MyNamespace.Program.IsOutsiteWestBoundary()")
where depth0  >= 0 orderby depth0
select new { m, depth0 }

Notice that the code query result also provides the depth of call. It can be stored in your NDepend project, and it can be transformed into a rule by adding the prefix warnif count > 0.

NDepend method call indirect

This query gets inspired from the query generated by NDepend when right clicking a method and Select Methods ... that call me (directly or indirectly).

NDepend method call indirect

If you click the button Export to Graph you get such call graph (more info on this here):

NDepend method call graph

A 14-day full featured trial is available here.

Disclaimer: I work for NDepend.