Pavani gaddam
Pavani gaddam

Reputation: 287

Measuring the number of methods in a class

I am supposed to count the number of methods in a class of any .NET program. For this I am making use of the il of that particular program. Initially I thought that I would count the number of "ret" in the il. But then I found out that even method declarations consists of the "ret" keyword. Then I tried to go with "callvirt". But this would not work in all the cases. Now I am thinking about something like this :-

Count the number of times the following appears in the il:- end of method class_name::method_name

but i don't know how to implement this (I am a complete newbie to .NET)

Can you kindly suggest an alternate way to identify a method in a class by making use of the il?

Upvotes: 1

Views: 811

Answers (3)

CodesInChaos
CodesInChaos

Reputation: 108790

My preferred methods:

Method 1:
Load the assemby into your AppDomain and use reflection. This executes code from the assembly(i.e. it should not be evil), and its dependencies must be resolvable too.

Method 2:
Load the assembly containing the class into Mono.Cecil, and then just enumerate the methods using its API.

Which of the two to choose depends on the context. If you have loaded/will load the assembly anyways, then use reflection. If you just want to analyze an assembly file, use Mono.Cecil.

Other methods:

Method 3:
Use CCI, I have no experience with this one. Looks similar to Mono.Cecil.

Method 4:
Use reflection-only assembly loading with reflection. I found this one to be painful, and recommend not using it.

Upvotes: 2

ken2k
ken2k

Reputation: 48975

As you're talking about IL, I assume you want to count the number of methods in a compiled assembly.

You could load your .Net assembly then use reflection to retrieve all methods.

See Get class methods using reflection

Upvotes: 0

Abbas
Abbas

Reputation: 14432

Two ways to do this:

//with an instance of the class
var instance = new YourClass();
var methods = instance.GetType().GetMethods();
var count = methods.Length;

//using the type of the class (no instance)
var classType = typeof(YourClass);
var methods = classType.GetMethods();
var count = methods.Length;

I've written this in several steps to make it understandable. Of course you can write it in one line. For example the second method looks like this then:

var count = typeof(YourClass).GetMethods().Length;

Hope this helps! :)

Upvotes: 1

Related Questions