Enumerating through an object’s properties (string) in C#

Use reflection. It’s nowhere near as fast as hardcoded property access, but it does what you want.

The following query generates an anonymous type with Name and Value properties for each string-typed property in the object ‘myObject’:

var stringPropertyNamesAndValues = myObject.GetType()
    .GetProperties()
    .Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null)
    .Select(pi => new 
    {
        Name = pi.Name,
        Value = pi.GetGetMethod().Invoke(myObject, null)
    });

Usage:

foreach (var pair in stringPropertyNamesAndValues)
{
    Console.WriteLine("Name: {0}", pair.Name);
    Console.WriteLine("Value: {0}", pair.Value);
}

Leave a Comment