Click here to Skip to main content
15,895,799 members
Articles / Properties
Article

How to iterate through all properties of a class

Rate me:
Please Sign up or sign in to vote.
4.20/5 (2 votes)
11 Oct 2013CPOL 94.9K   1   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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

754 members

Comments and Discussions

 
PraiseThank You Very Much Pin
alejandropereza11-Jul-19 9:35
alejandropereza11-Jul-19 9:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.