diff --git a/AMWD.Common/Extensions/EnumExtensions.cs b/AMWD.Common/Extensions/EnumExtensions.cs
index 1a5cece..ee4d431 100644
--- a/AMWD.Common/Extensions/EnumExtensions.cs
+++ b/AMWD.Common/Extensions/EnumExtensions.cs
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.ComponentModel;
+using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace System
@@ -40,5 +41,13 @@ namespace System
/// The description or the string representation of the value.
public static string GetDescription(this Enum value)
=> value.GetAttribute()?.Description ?? value.ToString();
+
+ ///
+ /// Returns the name from .
+ ///
+ /// The enum value.
+ /// The display name or the string representation of the value.
+ public static string GetDisplayName(this Enum value)
+ => value.GetAttribute()?.Name ?? value.ToString();
}
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6ab18bf..c477a82 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Added `directory.build.props` and `directory.build.targets`
+- Added `GetDisplayName()` extension for enums
+ (`DisplayAttribute(Name = "")`)
## [v1.10.0](https://git.am-wd.de/AM.WD/common/compare/v1.9.0...v1.10.0) - 2022-09-18
diff --git a/UnitTests/Common/Extensions/EnumExtensionsTests.cs b/UnitTests/Common/Extensions/EnumExtensionsTests.cs
index babac92..7f0cd93 100644
--- a/UnitTests/Common/Extensions/EnumExtensionsTests.cs
+++ b/UnitTests/Common/Extensions/EnumExtensionsTests.cs
@@ -1,7 +1,8 @@
using System;
+using System.ComponentModel.DataAnnotations;
using System.Linq;
-using UnitTests.Common.Utils;
using Microsoft.VisualStudio.TestTools.UnitTesting;
+using UnitTests.Common.Utils;
using DescriptionAttribute = System.ComponentModel.DescriptionAttribute;
namespace UnitTests.Common.Extensions
@@ -107,6 +108,22 @@ namespace UnitTests.Common.Extensions
Assert.IsFalse(list.Any());
}
+ [TestMethod]
+ public void ShouldReturnDisplayNameOrStringRepresentation()
+ {
+ // arrange
+ var enumWithDisplayName = TestEnum.Two;
+ var enumWithoutDisplayName = TestEnum.Zero;
+
+ // act
+ string displayName = enumWithDisplayName.GetDisplayName();
+ string noDisplayName = enumWithoutDisplayName.GetDisplayName();
+
+ // assert
+ Assert.AreEqual("Zwei", displayName);
+ Assert.AreEqual(enumWithoutDisplayName.ToString(), noDisplayName);
+ }
+
internal enum TestEnum
{
[CustomMultiple("nix")]
@@ -115,6 +132,7 @@ namespace UnitTests.Common.Extensions
Zero,
[Description("Eins")]
One,
+ [Display(Name = "Zwei")]
Two,
}
}