Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to iterate through all properties of a class

0.00/5 (No votes)
8 Aug 2009 1  
Reflection is an important capability of the .NET framework and enables you to get information about objects at runtime. In this article, we will

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

Reflection is an important capability of the .NET framework and enables you to get information about objects at runtime. In this article, we will iterate through all properties for a class named Person using reflection.

using System;
using System.Reflection;

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person();
        person.Age = 27;
        person.Name = "Fernando Vezzali";

        Type type = typeof(Person);
        PropertyInfo[] properties = type.GetProperties();
        foreach (PropertyInfo property in properties)
        {
            Console.WriteLine("{0} = {1}", property.Name, property.GetValue(person, null));
        }

        Console.Read();
    }
}

The Person class extends System.Object and does not implement any interface. It is a simple class used to store information about a person:

class Person
{
    private int age;
    private string name;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here