Here is some C# code to extract
values from an object instance when you don't know (or care) what properties are available. A possible use case is when you know you want to iterate over / use the properties of an object -- all of them, no matter what they are -- and you don't want to hard code their names. Perhaps you're dealing with an object where the object author regularly adds and updates properties.
//Person.cs: Random test class that exposes some properties
using System;
public class Person{
public string FirstName { get{return "Jeffrey";} }
public string LastName { get{return "Knight";} }
public int Age { get { return 35; } }
}
Now here's the main code. Short and sweet:
//Main.cs: code to reflect on a saturated instance of this class to get the values out
using System;
using System.Reflection;
public class Test{
public static void Main(){
Person p = new Person();
Type pType = p.GetType();
PropertyInfo[] propertyInfo = pType.GetProperties();
foreach(PropertyInfo prop in propertyInfo){
string propName = prop.Name;
object propValue = pType.GetProperty(propName).GetValue(p, null);
Console.WriteLine(String.Format("{0}:{1}", propName, propValue));
}
}
}
There's a certain poetic beauty to this code -- so often in programming you have to know exactly what you're asking for in a way that's very literal. Here, it's revealing itself to us without us having to know beforehand. There's a sort of Heideggerian "givenness" to it.
Output:
FirstName:Jeffrey
LastName:Knight
Age:35