Description
I'd like to NativeAOT compile a library that respects the EnumMemberAttribute. This attribute can be applied to enum fields to rename what the field name is used when serializing values of an enum.
The issue is, I can't statically know all the enum types that will be passed into my code. So I need to write code like this:
private static object ReplaceEnumValueByStringRepresentation(object source)
{
if(source is Enum enumValue && GetEnumName(enumValue) is string enumValueName)
{
return enumValueName;
}
return source;
}
private static string? GetEnumName<T>(T value) where T : Enum
{
var type = value.GetType();
if(Enum.GetName(type, value) is not { } name)
throw new ArgumentException($"Invalid Enum value {value} for enum of type {type}");
if(type.GetField(name)?.GetCustomAttribute<EnumMemberAttribute>() is { } attribute)
return attribute.Value;
return name.ToFirstCharacterLowerCase();
But I am getting a warning on value.GetType()
and using it to call type.GetField(name)
.
In talking with @MichalStrehovsky and @agocke, one recommendation is that since enum fields cannot be trimmed, we can suppress this warning.
We should document this so people can justify suppressing this warning.
Additionally, it would be great if the analysis tooling understood that since T : Enum
, and we are calling GetField
on a System.Type that is guaranteed to be an enum, we shouldn't warn.
Metadata
Metadata
Assignees
Type
Projects
Status