Skip to content

Commit 552f6f4

Browse files
authored
Add EnumExtensions (#8)
1 parent e79514f commit 552f6f4

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

NetChris.Core/EnumExtensions.cs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
using System;
2+
using System.ComponentModel.DataAnnotations;
3+
using System.Linq;
4+
using System.Reflection;
5+
6+
namespace NetChris.Core;
7+
8+
// https://stackoverflow.com/a/25109103/208990
9+
/// <summary>
10+
///
11+
/// </summary>
12+
public static class EnumExtensions
13+
{
14+
/// <summary>
15+
/// A generic extension method that aids in reflecting
16+
/// and retrieving any attribute that is applied to an `Enum`.
17+
/// </summary>
18+
/// <seealso href="https://stackoverflow.com/a/25109103/208990" />
19+
public static TAttribute? GetAttribute<TAttribute>(this Enum enumValue)
20+
where TAttribute : Attribute
21+
{
22+
return enumValue.GetType()
23+
.GetMember(enumValue.ToString())
24+
.First()
25+
.GetCustomAttribute<TAttribute>();
26+
}
27+
28+
/// <summary>
29+
/// Get the <see cref="DisplayAttribute.Name"/> value from an enum value.
30+
/// </summary>
31+
public static string GetDisplayName(this Enum enumValue)
32+
{
33+
string result;
34+
var attribute = enumValue.GetAttribute<DisplayAttribute>();
35+
36+
if (attribute?.Name == null)
37+
{
38+
result = enumValue.ToString();
39+
}
40+
else
41+
{
42+
result = attribute.Name;
43+
}
44+
45+
return result;
46+
}
47+
}

NetChris.Core/NetChris.Core.csproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@
2323
<SupportedPlatform Include="browser"/>
2424
</ItemGroup>
2525

26+
<ItemGroup>
27+
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
28+
</ItemGroup>
29+
2630
<ItemGroup>
2731
<None Include="Package-README.md">
2832
<PackagePath>/</PackagePath>

0 commit comments

Comments
 (0)