Is there a way in c# to loop over the properties of a class?
Basically I have a class that contains a large number of property\'s (it basically holds the results of
foreach (PropertyInfo prop in typeof(MyType).GetProperties())
{
Console.WriteLine(prop.Name);
}
this is how to loop over the properties in vb.net , its the same concept in c#, just translate the syntax:
Dim properties() As PropertyInfo = Me.GetType.GetProperties(BindingFlags.Public Or BindingFlags.Instance)
If properties IsNot Nothing AndAlso properties.Length > 0 Then
properties = properties.Except(baseProperties)
For Each p As PropertyInfo In properties
If p.Name <> "" Then
p.SetValue(Me, Date.Now, Nothing) 'user p.GetValue in your case
End If
Next
End If
string notes = "";
Type typModelCls = trans.GetType(); //trans is the object name
foreach (PropertyInfo prop in typModelCls.GetProperties())
{
notes = notes + prop.Name + " : " + prop.GetValue(trans, null) + ",";
}
notes = notes.Substring(0, notes.Length - 1);
We can then write the notes string as a column to the log table or to a file. You have to use System.Reflection to use PropertyInfo
getting values of properties from simple class object....
class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
var person1 = new Person
{
Name = "John",
Surname = "Doe",
Age = 47
};
var props = typeof(Person).GetProperties();
int counter = 0;
while (counter != props.Count())
{
Console.WriteLine(props.ElementAt(counter).GetValue(person1, null));
counter++;
}
}
}
var csv = string.Join(",",myObj
.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(p => p.GetValue(myObj, null).ToString())
.ToArray());