Click here to Skip to main content
15,513,441 members
Articles / Programming Languages / C#
Technical Blog
Posted 6 Jun 2011

Tagged as

Stats

133.8K views
7 bookmarked

Looping through Object's properties in C#

Rate me:
Please Sign up or sign in to vote.
3.57/5 (5 votes)
6 Jun 2011CPOL
Looping through object's properties in C#

Have you ever tried to make a dynamic test page? To build an HTML element that contains all the properties of a specific .NET object?

Well, I encountered this problem a couple of days ago and while searching Google, I barely found good matches. So I decided that for my sake, and yours, I will simply post a short explanation about how to do it, followed by a quick and simple example of how to loop though object properties in C#.

First I'll provide a short explanation about Reflection:
Reflection enables you to discover an object's properties, methods, events and properties values at run-time.  Reflection can give you a full mapping of an object (well, it's public data).

In order to use reflection, and to loop through the object's properties, we'll first have to import the namespace:

C#
using System.Reflection;

Now, let's say I have an object called User and this object has 2 public properties:

  1. UserID
  2. Name

My code will look something like this:

C#
int testID = 123456; 
User usr = new User(testID); // this is constructor to get user by ID
StringBuilder sb = new StringBuilder();

PropertyInfo[] properties = user.GetType().GetProperties();
foreach (PropertyInfo pi in properties)
{
    sb.Append(
        string.Format("Name: {0} | Value: {1}", 
                pi.Name, 
                pi.GetValue(user, null)
            ) 
    );
}
divResults.InnerText = sb.ToString();

This little piece of code will fill your HTML element with the properties names and values.

Have fun!
Elad.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionThere is a typo in the code Pin
Drilon Ahmetaj20-Oct-21 6:31
Drilon Ahmetaj20-Oct-21 6:31 
QuestionExcellent! Pin
Camilo Reyes27-Mar-16 3:27
professionalCamilo Reyes27-Mar-16 3:27 
GeneralMy vote of 3 Pin
Diamonddrake25-Feb-13 20:01
Diamonddrake25-Feb-13 20:01 
has a typo in the code, the pi.GetValue method uses the argument "user" which is defined as usr above, one of them is incorrect.

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.