c# - Define custom titles on properties of objects -


i have list of objects of class defined

public class person {     public string firstname { get; set; }     public string lastname { get; set; }     public int age { get; set; } }   var personlist = new list<person>(); personlist.add(new person    {         firstname = "alex",         lastname = "friedman",         age = 27    }); 

and output list table property name column header (full source code)

var propertyarray = typeof(t).getproperties(); foreach (var prop in propertyarray)      result.appendformat("<th>{0}</th>", prop.name);   

and

firstname  | lastname  | age ---------------------------------- alex         friedman    27 

i want have custom titles, like

first name | last name | age  

question: how define column titles each property of person class? should use custom attributes on properties or there better way?

this approach i'd in case. it's quite simple , self explaining:

 var propertyarray = typeof(t).getproperties();       foreach (var prop in propertyarray) {          foreach (var customattr in prop.getcustomattributes(true)) {           if (customattr displaynameattribute) {//<--- displayname             if (string.isnullorempty(headerstyle)) {               result.appendformat("<th>{0}</th>", (customattr displaynameattribute).displayname);             } else {               result.appendformat("<th class=\"{0}\">{1}</th>", headerstyle, (customattr displaynameattribute).displayname);             }             break;           }         }        } 

since linked extensionmethod uses reflection anyway, can modify header-formatting loop above.

the usage of attribute this:

public class person {     [displayname("first name")]     public string firstname {       get; set;     }      [displayname("last name")]     public string lastname {       get; set;     }     public int age {       get; set;     }   } 

Comments