Find all uses of a method (including via interface) using NDepend
Asked Answered
L

1

7

Using NDepend, how can I find all, direct and indirect, uses of a specific method or property?

In particular, I need to find usages that occur via an interface somewhere along the use path. Thanks!

Lanny answered 13/6, 2012 at 9:48 Comment(0)
L
7

Right clicking a method anywhere in the UI, and selecting the menu: Select Method... > ...that are using me (directly or indirectly) leads to a code query like:

from m in Methods 
let depth0 = m.DepthOfIsUsing("NUnit.Core.NUnitFramework+Assert.GetAssertCount()")
where depth0  >= 0 orderby depth0
select new { m, depth0 }

The problem is that such query gives indirect usage, but doesn't look for calls that occurs via an interface (or an overridden method declared in a base class).

Hopefully what you are asking for can be obtained with this query:

// Retrieve the target method by name
let methodTarget = Methods.WithFullName("NUnit.Core.NUnitFramework+Assert.GetAssertCount()").Single()

// Build a ICodeMetric<IMethod,ushort> representing the depth of indirect
// call of the target method.
let indirectCallDepth = 
   methodTarget.ToEnumerable()
   .FillIterative(
       methods => methods.SelectMany(
          m => m.MethodsCallingMe.Union(m.OverriddensBase)))

from m in indirectCallDepth.DefinitionDomain
select new { m, callDepth = indirectCallDepth[m]  }

The two corner stones of this query are:

  • The call to FillIterative() to select recursively the indirect call.
  • The call to the property IMethod.OverriddensBase, as its name suggests. For a method M this returns the enumerable of all method declared in a base class or an interface, overriden by M.
Lara answered 13/6, 2012 at 14:34 Comment(2)
Is it possible to generate graph from results of this query? the problem that I get is that usages through overrides are not shown...Abrasive
no for now edge on graph only shows "real" dependencies, this situation will evolveLara

© 2022 - 2024 — McMap. All rights reserved.