Created
April 6, 2012 13:27
Get System.ComponentModel.DescriptionAttribute value of T
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
public static class EnumHelper<T> | |
{ | |
public static string GetEnumDescription(T _enum) | |
{ | |
Type type = _enum.GetType(); | |
var memInfo = type.GetMember(_enum.ToString()); | |
if (memInfo.Length > 0) | |
{ | |
var attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false); | |
if (attrs.Length > 0) | |
{ | |
return ((DescriptionAttribute)attrs[0]).Description; | |
} | |
} | |
throw new ArgumentException("DescriptionAttribute for T is null"); | |
} | |
} |
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
[TestFixture] | |
public class EnumHelperTest : SetupTestFixture | |
{ | |
const string EnumDescription1 = "My First Enum"; | |
const string EnumDescription2 = "My Second Enum"; | |
public enum MyEnums | |
{ | |
[System.ComponentModel.Description(EnumDescription1)] | |
Enum1 = 1, | |
[System.ComponentModel.Description(EnumDescription2)] | |
Enum2 = 2 | |
} | |
public enum MyBumEnums | |
{ | |
Enum1 = 1, | |
Enum2 = 2 | |
} | |
[Test] | |
public void TestDescription() | |
{ | |
var description = EnumHelper<MyEnums>.GetEnumDescription(MyEnums.Enum2); | |
var description2 = EnumHelper<MyEnums>.GetEnumDescription(MyEnums.Enum1); | |
Assert.AreEqual(description, EnumDescription2); | |
Assert.AreEqual(description2, EnumDescription1); | |
} | |
[Test] | |
public void TestDescriptionIsEmpty() | |
{ | |
Assert.Throws<ArgumentException>(() => EnumHelper<MyBumEnums>.GetEnumDescription(MyBumEnums.Enum1)); | |
} | |
} |
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
[TestFixture] | |
public class SetupTestFixture | |
{ | |
private Stopwatch _s; | |
[SetUp] | |
public void SetUp() | |
{ | |
_s = new Stopwatch(); | |
_s.Start(); | |
} | |
[TearDown] | |
public void Teardown() | |
{ | |
_s.Stop(); | |
Console.Out.WriteLine("Time for test to complete: " + _s.ElapsedMilliseconds + "ms"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment