Add GetDisplayName to enum extensions
This commit is contained in:
@@ -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
|
||||
/// <returns>The description or the string representation of the value.</returns>
|
||||
public static string GetDescription(this Enum value)
|
||||
=> value.GetAttribute<DescriptionAttribute>()?.Description ?? value.ToString();
|
||||
|
||||
/// <summary>
|
||||
/// Returns the name from <see cref="DisplayAttribute"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">The enum value.</param>
|
||||
/// <returns>The display name or the string representation of the value.</returns>
|
||||
public static string GetDisplayName(this Enum value)
|
||||
=> value.GetAttribute<DisplayAttribute>()?.Name ?? value.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user