Skip to content

Instantly share code, notes, and snippets.

@benbrandt22
Created March 20, 2018 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save benbrandt22/d0426a20763b0d1b895c490a1f4a8479 to your computer and use it in GitHub Desktop.
Save benbrandt22/d0426a20763b0d1b895c490a1f4a8479 to your computer and use it in GitHub Desktop.
Auto-generating Display Name attribute - Splits camel-cased member names into space-separated words as a display name
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
namespace Demo.Attributes
{
/// <summary>
/// DisplayName attribute that auto-generates a display name from the member name, splitting CamelCase name into words.
/// </summary>
[AutoDisplayName]
public class AutoDisplayNameAttribute : DisplayNameAttribute
{
/// <summary>
/// DisplayName attribute that auto-generates a display name from the member name, splitting CamelCase name into words.
/// </summary>
/// <param name="callerMemberName">parameter that (when not explicitly used) automatically supplies the name of the member attached to this attribute</param>
public AutoDisplayNameAttribute([CallerMemberName] string callerMemberName = null) : base(CamelCaseToWords(callerMemberName))
{
}
private static string CamelCaseToWords(string callerMemberName)
{
return Regex.Replace(callerMemberName, @"(\B[A-Z]+?(?=[A-Z][^A-Z])|\B[A-Z]+?(?=[^A-Z]))", " $1");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment