Sorting Methods of Class using Reflection C#

Helps to Sort all the Methods from the Class.

public void SortingMethodsUsingReflection()
        {
            MethodInfo[] methodInfos = typeof(Student).GetMethods();

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

            // writes all the property names
            foreach (MethodInfo methodInfo in methodInfos)

            {
                Response.Write(methodInfo.Name + "<br/>");
            }
        }

OUTPUT:

Note it takes base class, current class and property as method if you don't set Binding Flags.

Equals
get_Grade
get_Name
GetHashCode
GetType
M1
M2
M3
set_Grade
set_Name
ToString

Used Class for Demo:

class Student
    {
        private string _name;
        private double _grade;

        public string Name

        {
            get { return _name; }
            set { _name = value; }
        }

        public double Grade
        {
            get { return _grade; }
            set { _grade = value; }
        }

        public void M1()
        {
            //Code
        }

        public void M2()
        {
            //Code
        }

        public string M3()
        {
            return string.Empty;
        }

        public Student(string name, double grade)
        {
            this.Name = name;
            this.Grade = grade;
        }
    }

Thanks for reading this article. Have a nice day.

Ebook Download
View all
Learn
View all