I am writing some code that will send an email with details of what is inside the properties of a class.
Instead of hard coding the rows with the properties, I thought it was best to do this via reflection
var builder = new StringBuilder();
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.GetValue(obj, null) != null)
{
builder.AppendLine("<tr>");
builder.AppendLine("<td>");
builder.AppendLine("<b> " + property.Name + " </b>");
builder.AppendLine("</td>");
builder.AppendLine("<td>");
builder.AppendLine(property.GetValue(obj, null).ToString());
builder.AppendLine("</td>");
builder.AppendLine("</tr>");
}
}
Which also helps leave out all the properties that hasn't been set which again helps to reduce code.
However property.Name quite rightly outputs the name of the property in its current form
public string PropertyA { get; set; }
So the Email would look like
PropertyA : 123
Which doesnt look friendly to the user. So is there a way I can change the property name to display something different?
I have tried
[DisplayName("Property A")]
public string PropertyA { get; set; }
which should look like in the email:
Property A : 123
But to no prevail.... Is there anything out there to help on the road of the logic I am going down?
Thanks