Hi @Ronald Rex , Welcome to Microsoft Q&A,
Are there any preconditions?
To iterate over all properties of a POCO class, you can use reflection. In C#, you can use the "Type" class to get information about the properties of an object type.
First use GetType() to get the type of the OrderPoco object. Then, use "GetProperties()" to retrieve an array of "PropertyInfo" objects that represent the class properties. Finally, iterate through the property information and use GetValue() to access the property's values and print them to the console.
Public properties available only for POCO classes. If you have private or protected properties, you will need to modify your code accordingly. In addition, using reflection may reduce performance and needs to be used with caution.
using System;
using System.Reflection;
class Program
{
static void Main()
{
var o = new OrderPoco()
{
OrderID = 1,
CustomerID = "ABCDE",
Shipper = 3
};
// Get the type of the object
Type type = o.GetType();
// Get all public properties of the object's type
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
// Get the name and value of each property
string propertyName = property.Name;
object propertyValue = property.GetValue(o);
Console.WriteLine($"{propertyName}: {propertyValue}");
}
}
}
class OrderPoco
{
public int OrderID { get; set; }
public string CustomerID { get; set; }
public int Shipper { get; set; }
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.