Last active
January 15, 2016 19:28
-
-
Save miklund/ce8db4b7b90ba47dbbae to your computer and use it in GitHub Desktop.
2009-02-20 The value of attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Title: The value of attributes | |
# Author: Mikael Lundin | |
# Link: http://blog.mikaellundin.name/2009/02/20/the-value-of-attributes.html |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Flags] | |
public enum Genre | |
{ | |
Other = 0, | |
AlternativeRock = 1, | |
HardRock = 2, | |
WorldMusic = 4, | |
Indie = 8, | |
PostRock = 16 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LabelAttribute : Attribute | |
{ | |
public LabelAttribute(string text) | |
{ | |
this.Text = text; | |
} | |
public string Text { get; set; } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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