views:

126

answers:

4

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?

A: 

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

Anton Gogolev
+5  A: 

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.)

Jon Skeet
@Jon - the bigger picture is an ORM type framework over MS CRM. Although we will be requiring the information at runtime a static analysis will be fine. I will investigate ndepend, thanks for the tip. I'll post back my findings hopefully in less than 6 months!). providing
Gareth D
+1  A: 

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.

Petar Repac
A: 

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:

Gareth D