You need to use reflection. Here’s a sample:
static void Main(string[] args)
{
string obj1 = "a string";
int obj2 = 12;
DateTime obj3 = DateTime.Today;
object[] obj_array = { obj1, obj2, obj3 };
foreach (object obj in obj_array)
{
//Print value
Console.WriteLine("Value: " + obj.ToString());
//Print property names
Console.WriteLine("Property Names:");
foreach (PropertyInfo prop in obj.GetType().GetProperties())
{
Console.WriteLine(prop.Name);
}
Console.WriteLine();
}
Console.Read();
}
EDIT: sorry you probably wanted to retrieve the property values of the object itself. In that case, here’s another sample:
class Program
{
static void Main(string[] args)
{
MyObject myobj = new MyObject("prop1", "prop2");
object[] obj_array = { myobj };
foreach (object obj in obj_array)
{
foreach (PropertyInfo property in obj.GetType().GetProperties())
{
Console.WriteLine("Property Name: " + property.Name);
Console.WriteLine("Property Value: " + property.GetValue(obj));
}
}
Console.Read();
}
}
public class MyObject
{
public string Property1 { get; set; }
public string Property2 { get; set; }
public MyObject(string p1, string p2)
{
Property1 = p1;
Property2 = p2;
}
}
solved Print out array of objects to console [closed]