Skip to content

Instantly share code, notes, and snippets.

@lukasz-madon
Created January 5, 2015 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukasz-madon/6cdccc543d8c80289d1e to your computer and use it in GitHub Desktop.
Save lukasz-madon/6cdccc543d8c80289d1e to your computer and use it in GitHub Desktop.
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