Question

Given two .Net types, type A and type B, how could one determine all property calls to type A (including sub classes of type A) made from type B?

Was it helpful?

Solution

You'd have to find all the executable members (methods, properties, events, constructors) and call MethodInfo.GetMethodBody to get the raw IL. Then parse that IL and look for access to properties. Don't forget to get virtual methods declared in base classes as well.

Good luck - see you in 6 months! Seriously, this isn't going to be easy, and sounds like an unusual requirement. What's the bigger picture here?

If you don't need to do this at execution time, but just want to see dependencies, you may find that NDepend will help you. (Heck, maybe NDepend exposes an API you can use to do it at execution time - worth checking, I suppose.)

OTHER TIPS

According to this blog entry Mono.Cecil vs. System.Reflection from Patrick Smacchia's blog NDepend uses Mono.Cecil to analyze assemblies.

Maybe it could be useful.

You can do that using StackFrame and StackTrace classes, but that is generally considered to be a bad practice.

The solution involves static analysis of the code - essentially we are looking for dependencies on type A in type B. Out of the box the .Net reflection APIs can only take you so far before you have to resort to parsing the IL - as Jon notes below this is not to be taken lightly. The answers below have led to a couple of libraries that may help, I will be investigating them both:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top