Skip to content

Instantly share code, notes, and snippets.

@miklund
Last active January 15, 2016 19:28
Show Gist options
  • Save miklund/ce8db4b7b90ba47dbbae to your computer and use it in GitHub Desktop.
Save miklund/ce8db4b7b90ba47dbbae to your computer and use it in GitHub Desktop.
2009-02-20 The value of attributes
# Title: The value of attributes
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2009/02/20/the-value-of-attributes.html
[Flags]
public enum Genre
{
Other = 0,
AlternativeRock = 1,
HardRock = 2,
WorldMusic = 4,
Indie = 8,
PostRock = 16
}
[Flags]
public enum Genre
{
[Label("Other")]
Other = 0,
[Label("Alternative Rock")]
AlternativeRock = 1,
[Label("Hard rock")]
HardRock = 2,
[Label("World music")]
WorldMusic = 4,
[Label("Indie")]
Indie = 8,
[Label("Post-rock")]
PostRock = 16
}
public class LabelAttribute : Attribute
{
public LabelAttribute(string text)
{
this.Text = text;
}
public string Text { get; set; }
}
public static class LabelAttributeHelper
{
/// <summary>
/// Get label of an enum field
/// </summary>
public static string Label<T>(this T val)
{
if (!typeof(T).IsEnum)
throw new ArgumentException("T must be an Enum");
FieldInfo field = typeof(T).GetField(val.ToString());
LabelAttribute[] attributes =
(LabelAttribute[])field.GetCustomAttributes(typeof(LabelAttribute), false);
if (attributes.Length == 0)
throw new ArgumentOutOfRangeException("Enum value " + val.ToString() + " is missing Label attribute");
return attributes.First().Text;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment