Reputation: 636
I have a Class Data which has a protomember ReportName defined with a slightly different display name so that the grid column headers are more meaningful .
Now i am implementing IDataErrorInfo to this class to display an error message to the end user saying 'Report Name cannot be null' while saving . So how do i access the display member attribute of ReportName in a private method of the same class?
Class Data
{
[ProtoMember(1), DefaultValue(null), DisplayName("Report Name")]
public string ReportName { get; set; }
//Check if the reportname was entered
private void CheckReportName()
{
//code to check reportname and generate the errormessage containing the colheader to be sent to grid
}
}
Ho
Upvotes: 0
Views: 74
Reputation: 27515
Given that Reflection already requires a 'magic string' for the property name to look up the value, you might consider something like this instead:
class Data
{
[ProtoMember(1), DefaultValue(null), DisplayName(DisplayNames.ReportName)]
public string ReportName { get; set; }
//Check if the reportname was entered
private void CheckReportName()
{
//code to check reportname and generate the errormessage containing the colheader to be sent to grid
}
private static class DisplayNames
{
public const string ReportName = "Report Name";
}
}
This executes faster than the Reflection-based approach and (more importantly) it avoids using a hard-coded property name for getting the property to find the attribute.
Upvotes: 0
Reputation: 57129
You can use reflection:
var displayName = this.GetType()
.GetProperty("ReportName")
.GetCustomAttributes(false)
.OfType<DisplayNameAttribute>()
.First()
.DisplayNameValue;
Upvotes: 1