How to iterate thought all properties of a class

Vezzali
Posted by in .NET Framework category on for Intermediate level | Views : 20824 red flag

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


 Download source code for How to iterate thought all properties of a class

Introduction

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

Reflection

Reflection is an important resource of the Microsoft Framework, for example,
enables us to get some information about object in runtime, in this article
we will iterate thought all properties of a class named Person, using Reflection.

Person is a simple class, used just to hold information about a Person.

The following C# .Net code shows how to do it.

Example Code

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; }
    }
}
 

Conclusion

The Person class extends object and does not implement any interface. 
Using reflection we can iterate thought all properties.


Page copy protected against web site content infringement by Copyscape

About the Author

Vezzali
Full Name: Fernando Vezzali
Member Level: Starter
Member Status: Member
Member Since: 9/7/2008 1:13:55 AM
Country:

http://weblogs.asp.net/fernandovezzali

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)