How to get the User defined methods from class [Resolved]

Posted by Vijay1987 under C# on 9/21/2015 | Points: 10 | Views : 458 | Status : [Member] | Replies : 3
I am compiling the c# code at run time using "Reflection" and trying to get the methods names. I am able to get the user defined methods and also predefined methods. But I want get the only the user defined methods.

My code :
Assembly assembly = results.CompiledAssembly;
var names = (from type in assembly.GetTypes()
from method in type.GetMethods(
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static)
select method.Name).Distinct().ToList();
Can any one help me.

Thanks in Advance.




Responses

Posted by: Vijay1987 on: 9/22/2015 [Member] Starter | Points: 25

Up
1
Down

Resolved
Thanks for reply Niladri Biswas.

I have solved the problem using below code

var names = (from type in assembly.GetTypes()
from method in type.GetMethods(
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly)
select method.Name).Distinct().ToList();



Vijay1987, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 9/21/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 25

Up
1
Down
Try

......ToList().Where(m => !m.IsSpecialName 

&& !m.IsVirtual
&& m.MethodImplementationFlags== MethodImplAttributes.IL
)


This solution assumes that you don't have any overridden methods.

--
Thanks & Regards,
RNA Team

Vijay1987, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 9/22/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 25

Up
1
Down
@Vijay187, this will not work out if you have some properties defined in your class. Those will appear as setter and getter methods. In that case you have to use
.Where(m => !m.IsSpecialName )
along with
BindingFlags.DeclaredOnly


--
Thanks & Regards,
RNA Team

Vijay1987, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response