Skip to content

Instantly share code, notes, and snippets.

@codercampos
Last active May 15, 2023 21:25
Show Gist options
  • Save codercampos/4ee6af6fed92fcb70a04139d839fad3c to your computer and use it in GitHub Desktop.
Save codercampos/4ee6af6fed92fcb70a04139d839fad3c to your computer and use it in GitHub Desktop.
Get DisplayName attribute's value from a property.
using System.ComponentModel;
using System.Reflection;
namespace YourApp.Extensions;
public class ReflectionHelpers
{
/// <summary>
/// Get's the string value of the DisplayName attribute of a property.
/// </summary>
/// <typeparam name="T">The type of the object the property is part of</typeparam>
/// <param name="propertyName">The property name We are looking for.</param>
/// <returns>The value of the property's DisplayName attribute.</returns>
/// <exception cref="ArgumentException">Throws this exception if the property does not exists, the parameter is null or does not have a DisplayName attribute.</exception>
public static string GetDisplayName<T>(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
throw new ArgumentException("Property name should not be empty");
Type type = typeof(T);
PropertyInfo? propertyInfo = type.GetProperty(propertyName);
if (propertyInfo == null)
throw new ArgumentException($"The property {propertyName} does not exists");
Attribute? attribute = propertyInfo
.GetCustomAttributes(typeof(DisplayNameAttribute)).SingleOrDefault();
if (attribute == null)
throw new ArgumentException($"The property {propertyName} does not have display name attribute");
return ((DisplayNameAttribute)attribute).DisplayName;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment