0

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

user3428422
  • 4,300
  • 12
  • 55
  • 119

2 Answers2

2

You need to find the attribute and extract the Name value:

var displayNameAttribute = property.GetCustomAttributes
                                    (typeof(DisplayNameAttribute), false)
                                    .FirstOrDefault() as DisplayNameAttribute;

string displayName = displayNameAttribute != null 
                         ? displayNameAttribute.DisplayName 
                         : property.Name;
Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • Thanks, the same as I said for the first answer, its not `attribute.Name` its `attribute.DisplayName` well for me... – user3428422 Nov 05 '14 at 15:50
  • Thanks, fixed. The `GetCustomAttribute<>()` extension method proposed by @Selman22 has a somewhat nicer syntax though. – CodeCaster Nov 05 '14 at 15:57
  • In a way I agree, but you do the null check within a :? operator, however, I am not that picky to be honest, I can award the answer to @Selman22. I just normally award it on whom answers first but both of your answers are basically the same.. – user3428422 Nov 05 '14 at 16:00
2

You need to get DisplayNameAttribute of your property and then get it's Name:

var attribute = property.GetCustomAttribute<DisplayNameAttribute>();

if(attribute != null)
{
   var displayName = attribute.Name;
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184