0

How may I reflect a type to check if it has any method in it that calls, say, the InterlockedExchange.Compare method?

My guess is that it's not possible using simply reflection. I might need to use Roslyn or Mono.Cecil.

private static bool HasOneOrMoreMethodsThatCallInterlockedExchangeCompare(Type type)
{
    if (type == null)
    {
        throw new ArgumentNullException(nameof(type));
    }

    if (!type.IsClass) return false;

    var methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
    foreach (var method in methods)
    {
        var methodBody = method.GetMethodBody();

        // This is where I need help
    }

    return true;
}
Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336
  • @Eser Why is it a poor question? I know reflection and I know that it's not possible using reflection. I am trying to get a confirmation that it isn't and to find out what else to use. It's not as easy a question as it appears. – Water Cooler v2 Mar 31 '18 at 22:28
  • [This](https://stackoverflow.com/a/2693922/2193020) would seem to be confirmation that it's not possible. – hnefatl Mar 31 '18 at 22:28
  • 1
    Possible duplicate of [Look if a method is called inside a method using reflection](https://stackoverflow.com/questions/5741350/look-if-a-method-is-called-inside-a-method-using-reflection) - although this might be out-of-date. The top answer does have a code snippet that looks like it does exactly what you want though. – hnefatl Mar 31 '18 at 22:32
  • @Eser As you can see with the answer that hnefati linked to also, that answer also air brushes the issue. A very specific answer to my question would be enormously helpful to everyone. It's not as simple as it seems to be. – Water Cooler v2 Mar 31 '18 at 22:32
  • 1
    So why not place a bounty on the existing question? – Stephen Kennedy Mar 31 '18 at 22:35
  • 1
    You have to decompile the IL. Sure, there are libraries for that, like Mono.Cecil. You still don't know if it is going to actually happen, the call might appear inside an if-statement. You can't solve that Halting Problem. – Hans Passant Mar 31 '18 at 23:24
  • Is what you want, Find All References? – Jeremy Thompson Apr 01 '18 at 01:31
  • It should be possible, ildasm does not perform any magic. I found a pretty old codeproject article, https://www.codeproject.com/articles/14058/parsing-the-il-of-a-method-body. This may not work on more recent versions, give it a shot. – Tanveer Badar Apr 01 '18 at 07:59

0 Answers0