Hi experts,
Is there a way to know whether a C# method of a object is called or not using reflection?
Hi experts,
Is there a way to know whether a C# method of a object is called or not using reflection?
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)
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.
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).
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.
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.