C# – Get properties and values from unknown object


From the world of PHP I have decided to give C# a go. I've had a search but can't seem to find the answer of how to do the equivalent to this.

$object = new Object();

$vars = get_class_vars(get_class($object));

foreach($vars as $var)

I basically have a List of an object. The object could be one of three different types and will have a set of public properties. I want to be able to get a list of the properties for the object, loop over them and then write them out to a file.
I'm thinking this has something to do with c# reflection but it's all new to me.

Any help would be greatly appreciated.

Best Solution

This should do it:

Type myType = myObject.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

foreach (PropertyInfo prop in props)
    object propValue = prop.GetValue(myObject, null);

    // Do something with propValue