Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use ConcurrentDictionary For Improving Get Enum Name #1759

Merged
merged 1 commit into from
Aug 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions src/Microsoft.OpenApi/Extensions/EnumExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT license.

using System;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
Expand All @@ -14,6 +15,9 @@ namespace Microsoft.OpenApi.Extensions
/// </summary>
public static class EnumExtensions
{
// Cache to store display names of enum values
private static readonly ConcurrentDictionary<Enum, string> DisplayNameCache = new();

/// <summary>
/// Gets an attribute on an enum field value.
/// </summary>
Expand All @@ -26,7 +30,13 @@ public static class EnumExtensions
public static T GetAttributeOfType<T>(this Enum enumValue) where T : Attribute
{
var type = enumValue.GetType();
// Use GetField to get the field info for the enum value
var memInfo = type.GetField(enumValue.ToString(), BindingFlags.Public | BindingFlags.Static);

if (memInfo == null)
return null;

// Retrieve the custom attributes of type T
var attributes = memInfo.GetCustomAttributes<T>(false);
return attributes.FirstOrDefault();
}
Expand All @@ -36,13 +46,20 @@ public static T GetAttributeOfType<T>(this Enum enumValue) where T : Attribute
/// </summary>
/// <param name="enumValue">The enum value.</param>
/// <returns>
/// Use <see cref="DisplayAttribute"/> if exists.
/// Use <see cref="DisplayAttribute"/> if it exists.
/// Otherwise, use the standard string representation.
/// </returns>
public static string GetDisplayName(this Enum enumValue)
{
var attribute = enumValue.GetAttributeOfType<DisplayAttribute>();
return attribute == null ? enumValue.ToString() : attribute.Name;
// Retrieve the display name from the cache if it exists
return DisplayNameCache.GetOrAdd(enumValue, e =>
{
// Get the DisplayAttribute
var attribute = e.GetAttributeOfType<DisplayAttribute>();

// Return the DisplayAttribute name if it exists, otherwise return the enum's string representation
return attribute == null ? e.ToString() : attribute.Name;
});
}
}
}
Loading