How to iterate through all the properties of a class in C#

How to iterate through all the properties of a class in C#? Use Reflection. And there are some differences between iterating through a instance of a class and iterating through a static class.

Here are the examples:

using System;
using System.Reflection;

namespace Learning
{
    class Inspector
    {
        static void Main()
        {
            A a = new A() { PropA = "A", PropB = "B", PropC = "C" };
            Console.WriteLine("Information of A:");
            InspectObject(a);
            Console.WriteLine();
            Console.WriteLine("Information of B:");
            InspectObject();
            Console.ReadKey();
        }

        private static void InspectObject(T o)
        {
            foreach (PropertyInfo prop in o.GetType().GetProperties())
            {
                Console.WriteLine("{0}: {1}", prop.Name, prop.GetValue(o, null));
            }
        }

        private static void InspectObject()
        {
            foreach (PropertyInfo prop in typeof(T).GetProperties())
            {
                Console.WriteLine("{0}: {1}", prop.Name, prop.GetValue(typeof(T), null));
            }
        }
    }

    class A
    {
        public string PropA { get; set; }
        public string PropB { get; set; }
        public string PropC { get; set; }
    }

    class B
    {
        public static string PropA { get { return "A"; } }
        public static string PropB { get { return "B"; } }
        public static string PropC { get { return "C"; } }
    }
}

Result:

image

Add comment

Loading