Skip to content

Commit f13a976

Browse files
authored
Fix Trim analysis warning IL2075: Elastic.Transport.Extensions.EnumExtensions.GetEnumName(Enum) (#172)
1 parent 143ef3b commit f13a976

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

examples/transport-aot-example/transport-aot-example.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
<Nullable>enable</Nullable>
99
<PublishAot>true</PublishAot>
1010
<TrimmerSingleWarn>false</TrimmerSingleWarn>
11+
<WarningsAsErrors>true</WarningsAsErrors>
1112
</PropertyGroup>
1213

1314
<ItemGroup>

src/Elastic.Transport/Extensions/Extensions.cs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
using System;
66
using System.Collections.Generic;
7+
using System.Diagnostics.CodeAnalysis;
78
using System.Globalization;
89
using System.IO;
910
using System.Linq;
@@ -14,15 +15,23 @@ namespace Elastic.Transport.Extensions;
1415

1516
internal static class EnumExtensions
1617
{
17-
public static string GetEnumName(this Enum e)
18+
/*
19+
* Fields on enums are preserved but the compiler is too aggressive.
20+
* Fixed in https://github.com/dotnet/runtime/pull/100814 (presumably .NET 9 or 10)
21+
*/
22+
[UnconditionalSuppressMessage("AssemblyLoadTrimming", "IL2075:DynamicallyAccessMembers", Justification = "Fields on enum are preserved by trimmer")]
23+
public static string GetEnumName<T>(this T e)
24+
where T : Enum
1825
{
19-
var attributes = e.GetType().GetField(e.ToString())?.GetCustomAttributes(typeof(EnumMemberAttribute), false);
26+
var type = e.GetType();
27+
var attributes = type.GetField(e.ToString())?.GetCustomAttributes(typeof(EnumMemberAttribute), false);
2028
if (attributes is null || attributes.Length == 0)
2129
return e.ToString();
2230

2331
var enumMember = attributes[0] as EnumMemberAttribute;
2432
return enumMember?.Value ?? e.ToString();
2533
}
34+
2635
}
2736

2837
internal static class Extensions

0 commit comments

Comments
 (0)