Created
January 5, 2015 12:30
-
-
Save lukasz-madon/6cdccc543d8c80289d1e to your computer and use it in GitHub Desktop.
This file contains 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
using System; | |
using System.Linq; | |
namespace EnumTest | |
{ | |
public enum ContentAreaTagEnum | |
{ | |
Unknown, | |
[ContentArea(Name = "Full")] | |
Full, | |
[ContentArea(Name = "23rd")] | |
TwoThirds, | |
[ContentArea(Name = "Half")] | |
Half | |
} | |
public class ContentAreaAttribute : Attribute | |
{ | |
public string Name { get; set; } | |
} | |
public static class EnumExtensions | |
{ | |
public static T GetFirstAttribute<T>(this Enum enumValue) where T : Attribute | |
{ | |
var enumMemberInfo = enumValue.GetType().GetMember(enumValue.ToString()); | |
var first = enumMemberInfo.FirstOrDefault(); | |
// ReSharper disable once PossibleNullReferenceException This is only null when someone defines empty. Enum. I don't suspect someone doing such pointless thing. | |
var attributes = first.GetCustomAttributes(typeof(T), false); | |
return (T)attributes.FirstOrDefault(); // resharper says the left operand is never null. Lib has a type hints. | |
} | |
} | |
public enum Empty{} | |
public enum SingleEnum{ X } | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine(ContentAreaTagEnum.Full.GetFirstAttribute<ContentAreaAttribute>().Name); | |
Console.WriteLine(ContentAreaTagEnum.TwoThirds.GetFirstAttribute<ContentAreaAttribute>().Name); | |
Console.WriteLine(ContentAreaTagEnum.Unknown.GetFirstAttribute<ContentAreaAttribute>() == null); | |
Console.WriteLine(SingleEnum.X.GetFirstAttribute<ContentAreaAttribute>()); | |
Empty x = 0; | |
Console.WriteLine(x.GetFirstAttribute<ContentAreaAttribute>()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment