22// Licensed under the MIT license.
33
44using System ;
5+ using System . Collections . Concurrent ;
56using System . Diagnostics . CodeAnalysis ;
67using System . Linq ;
78using System . Reflection ;
@@ -14,6 +15,9 @@ namespace Microsoft.OpenApi.Extensions
1415 /// </summary>
1516 public static class EnumExtensions
1617 {
18+ // Cache to store display names of enum values
19+ private static readonly ConcurrentDictionary < Enum , string > DisplayNameCache = new ( ) ;
20+
1721 /// <summary>
1822 /// Gets an attribute on an enum field value.
1923 /// </summary>
@@ -26,7 +30,13 @@ public static class EnumExtensions
2630 public static T GetAttributeOfType < T > ( this Enum enumValue ) where T : Attribute
2731 {
2832 var type = enumValue . GetType ( ) ;
33+ // Use GetField to get the field info for the enum value
2934 var memInfo = type . GetField ( enumValue . ToString ( ) , BindingFlags . Public | BindingFlags . Static ) ;
35+
36+ if ( memInfo == null )
37+ return null ;
38+
39+ // Retrieve the custom attributes of type T
3040 var attributes = memInfo . GetCustomAttributes < T > ( false ) ;
3141 return attributes . FirstOrDefault ( ) ;
3242 }
@@ -36,13 +46,20 @@ public static T GetAttributeOfType<T>(this Enum enumValue) where T : Attribute
3646 /// </summary>
3747 /// <param name="enumValue">The enum value.</param>
3848 /// <returns>
39- /// Use <see cref="DisplayAttribute"/> if exists.
49+ /// Use <see cref="DisplayAttribute"/> if it exists.
4050 /// Otherwise, use the standard string representation.
4151 /// </returns>
4252 public static string GetDisplayName ( this Enum enumValue )
4353 {
44- var attribute = enumValue . GetAttributeOfType < DisplayAttribute > ( ) ;
45- return attribute == null ? enumValue . ToString ( ) : attribute . Name ;
54+ // Retrieve the display name from the cache if it exists
55+ return DisplayNameCache . GetOrAdd ( enumValue , e =>
56+ {
57+ // Get the DisplayAttribute
58+ var attribute = e . GetAttributeOfType < DisplayAttribute > ( ) ;
59+
60+ // Return the DisplayAttribute name if it exists, otherwise return the enum's string representation
61+ return attribute == null ? e . ToString ( ) : attribute . Name ;
62+ } ) ;
4663 }
4764 }
4865}
0 commit comments