Friday, 29 November 2013

Get Method Names using Reflection [C#]

Leave a Comment
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="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html> 


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 |
                               BindingFlags.Instance
                               );

            // sort methods by name
            Array.Sort(methodInfos,
                    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



By
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 =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.