tags:

views:

72

answers:

5

Hi experts,

Is there a way to know whether a C# method of a object is called or not using reflection?

A: 

No. Reflection only know how a type is constructed and not how it's called by your application.

You can create an array of StackFrame inside a method to know how it was called.

Resharper can check if a method is called or not (it's a Visual Studio plugin)

jgauffin
I doubt Resharper can tell with 100% accuracy.
Jonas Elfström
I did not claim that it would, did I? Although it does a very good job as long as all assemblies are in the same solution.
jgauffin
A: 

If your question is about how to find out whether a specific method will ever be called in any scenario and for any input, then reflection can't do it for you.

You need tools to do the static program analysis, but these are not quite meant to be used at runtime.

If you could describe in more details what you're trying to accomplish, we might suggest an alternative.

Developer Art
+1  A: 

One way to find out if your method is called is to use a code coverage tool. Visual studio Ultimate contains such tools to help determine code coverage. You first instrument your code, and then run your tests, or exercise your app normally, and then check your results.

Or you can just use a text editor to search for the method name in your source code. (That is by far the easiest).

C Johnson
+1  A: 

You could add a line of code to your method:

System.Diagnostics.Debug.WriteLine("MyMethod was called with xx param values");

If you are debugging in Visual Studio, in the Debug menu, under the "Windows" section, choose the Output window.

If the method is called, then "MyMethod was called with xx param values" will appear in there.

Neil Fenwick
this would require editing **all** the methods and it's quite cumbersome.
devnull
Neil Fenwick
A: 

If you want to find any methods in your assembly that are never called by any other part of the assembly, FxCop has a "dead code" rule that will find any such methods.

The dead code search does not include methods which can be called from the outside world, such as public methods though.

Jonny Cundall