How to iterate thought all properties of a class

 Rate It (3)

The purpose of this article is to describe some of the practical uses of the Reflection.

Reflection is an important resource of the .NET Framework and enables us to get information about objects at runtime. In this article we will iterate thought all of the properties of a class named Person using Reflection.

The Person class extends object and does not implement any interface. It is a simple class used just to hold information about a Person.

The following C# .NET code shows how to do it. (or download the solution: http://weblogs.asp.net/blogs/fernandovezzali/ReflectionProject.zip)

class Program
{
    static void Main(string[] args)
    {
        Person oPerson = new Person();
        oPerson.iAge = 27;
        oPerson.sName = "Fernando Vezzali";
        PropertyInfo[] properties = oPerson.GetType().GetProperties();
        foreach (PropertyInfo oPropertyInfo in properties)
        {
            MethodInfo oMethodInfo = oPerson.GetType().GetMethod("get_" + oPropertyInfo.Name);
            ParameterInfo[] ArrParameterInfo = oPerson.GetType().GetMethod("get_" + oPropertyInfo.Name).GetParameters();
            Console.WriteLine(oPropertyInfo.Name + " = " + oMethodInfo.Invoke(oPerson, ArrParameterInfo));
        }
        Console.Read();
    }
}

class Person
{
    private int _iAge;
    private string _sName;

    public int iAge
    {
        get { return _iAge; }
        set { _iAge = value; }
    }
    public string sName
    {
        get { return _sName; }
        set { _sName = value; }
    }
}

Revision number 2, Sunday, September 07, 2008 8:51:48 PM by mbanavige

Comments

This is cool. Two thumbs up!

What does this have to do with ASP.NET?

@joechung: While the example in this article currently uses a console app for demonstration purposes, reflection is still an applicable (and powerful) technique that can be used in ASP.NET web apps.

In This Section

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. mbanavige (5)
  2. SGWellens (4)
  3. maartenba (2)
  4. rami_nassar (2)
  5. stiansol (2)
  6. MisterFantastic (2)
  7. satish1.v (1)
  8. raklos (1)
  9. mosessaur (1)
  10. Jos Branders (1)

Advertise Here

Microsoft Communities
Page view counter