Sorting Properties of Class using Reflection C#

Helps to Sort all the Properties from the Class.

 public void SortingPropertiesUsingReflection()
        {
            PropertyInfo[] propertyInfos = typeof(Student).GetProperties();

            //Sorting property Name
            Array.Sort(propertyInfos,
                   delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
                   { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });

            // writes all the property names
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                Response.Write(propertyInfo.Name + "<br/>");
            }
        }

Output:

Grade
Name

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