Get Method Names using Reflection [C#]

If you want to get method names of a given type in C#, you can use method Type.GetMethods. This method returns array of MethodInfo objects. MethodInfo contains many informations about the method and of course a method name (MethodInfo.Name).

To filter returned methods (for example if you want to get only public static methods) use BindingFlags parameter when calling GetMethods method. Required are at least two flags, one from Public/NonPublic and one of Instance/Static flags. Of course you can use all four flags and also DeclaredOnly and FlattenHierarchy. BindingFlags enumeration and MethodInfo class are declared in System.Reflection namespace.

The example will show method name and return type of the method of developersnote class

The developersnote Class

    public class developersnoteClass
        public developersnoteClass()
        public void ConvertDateTime()
        public static void ConvertInteger()
        public static void FormatString()
        public void FormatDouble()

The ASPX Page

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">

The Code Behind

       protected void Page_Load(object sender, EventArgs e)
            // get all public static methods of MyClass type
            MethodInfo[] methodInfos = typeof(developersnoteClass).GetMethods(BindingFlags.Public |
                               BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod |

            // sort methods by name
                    delegate(MethodInfo methodInfo1, MethodInfo methodInfo2)
                    { return methodInfo1.Name.CompareTo(methodInfo2.Name); });

            // write method names
            foreach (MethodInfo methodInfo in methodInfos)
                Response.Write(methodInfo.ReturnType + " "  +  methodInfo.Name  + "<br/>");

The Output

NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

Phone book application example - Java

Modal Popup Message Box ASP.NEt C# Example