fresky
fresky

Reputation: 540

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

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

Upvotes: 1

Views: 199

Answers (4)

Jonny Cundall
Jonny Cundall

Reputation: 2612

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.

Upvotes: 0

C.J.
C.J.

Reputation: 16081

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

Upvotes: 1

user151323
user151323

Reputation:

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.

Upvotes: 0

jgauffin
jgauffin

Reputation: 101140

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)

Upvotes: 0

Related Questions