Deborah's Developer MindScape

         Tips and Techniques for Web and .NET developers.

August 29, 2010

Iterate Through the Properties of a Class

Filed under: C#,VB.NET @ 12:12 am

Reflection provides features to obtain information about loaded assemblies and the classes (and other types) within them. One of the many things you can do with reflection is to iterate through each of the properties of a class and access its values.

This example uses a customer class.

In C#:

public class Customer
    public int CustomerId { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string EmailAddress { get; set; }
    private string myPrivateProperty { get; set; }

In VB:

Public Class Customer
    Public Property CustomerId As Integer
    Public Property FirstName() As String
    Public Property LastName() As String
    Public Property EmailAddress() As String
    Private Property myPrivateProperty() As String
End Class

First, get the type of the instance. Then use reflection to access all of the properties of the class.

Be sure to import the System.Reflection namespace.

In C#:

// Create a customer instance
Customer cust = new Customer()
    CustomerId = 5,
    FirstName = "Bilbo",
    LastName = "Baggins",
    EmailAddress = ""

// Get the type of this instance
Type t = cust.GetType();
string fieldName;
object propertyValue;

// Use each property of the business object passed in
foreach (PropertyInfo pi in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
    // Get the name and value of the property
    fieldName = pi.Name;

    // Get the value of the property
    propertyValue = pi.GetValue(cust, null);
    Console.WriteLine(fieldName + ": " +
       (propertyValue==null ? "null" : propertyValue.ToString()));

In VB:

‘ Create a customer instance
Dim cust As New Customer With {.CustomerId = 5,
                               .FirstName = "Bilbo",
                               .LastName = "Baggins",
                               .EmailAddress = ""}

‘ Get the type of this instance
Dim t As Type = cust.GetType
Dim fieldName As String
Dim propertyValue As Object

‘ Use each property of the business object passed in
For Each pi As PropertyInfo In t.GetProperties(BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic)
    ‘ Get the name and value of the property
    fieldName = pi.Name

    ‘ Get the value of the property
    propertyValue = pi.GetValue(cust, Nothing)
    Console.WriteLine(fieldName & ": " &
      If(propertyValue Is Nothing, "Nothing", propertyValue.ToString))

This code first creates an instance of the customer class for testing purposes. Then it gets the type of that instance using GetType. This code work on any class.

The GetProperties method retrieves the set of properties for that type based on the binding flags. Use an Or to combine binding flags.

The most commonly used binding flags are:

  • Instance: Includes instance members.
  • Static: Includes static (shared) members.
  • Public:Includes public instance members.
  • NonPublic: Includes non-public (private, protected, etc) members.

NOTE: You must include either Instance or Static (or both) to get a return value from GetProperties.

The GetProperties method returns an array of PropertyInfo objects that each provide information on one of the properties. The Name property of the PropertyInfo object provides the property name. The GetValue method returns the value of the property. Since the property could be any type, the GetValue returns an object.

Though not shown in this example, the SetValue method of the PropertyInfo object sets the value of a property.

Use this technique any time you need to loop through all of the properties of an object.

For example, you could use this technique to read through the set of properties of an object and build the parameters for an Insert or Update stored procedure or build a SQL statement. Or you could read a DataTable and use the SetValue method to set the value of each property to a matching field in the DataTable.



  1.   Bell — January 4, 2016 @ 12:24 pm    Reply

    After going over a number of the blog articles
    on your web site, I seriously appreciate your way of blogging.
    I saved as a favorite it tto my bookmark webpage list and will be checking
    back soon. Please check out my website as well and
    let mee know hhow you feel.

  2.   jason — February 24, 2016 @ 8:55 am    Reply

    I will immediately seize your rss feed as I can’t to find your email subscription hyperlink or e-newsletter service.
    Do you’ve any? Please permit me know in order that I may subscribe.

  3.   devenir riche — January 5, 2017 @ 11:34 am    Reply

    Every weekend i used to go to see this site, bdcause i want enjoyment, for
    the reaon that this this website conations truly pleasant funny material too.

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2020 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs