Skip to content

Respecting EnumMemberAttribute in AOT'd applications #97737

@eerhardt

Description

@eerhardt

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:

https://github.com/microsoft/kiota-abstractions-dotnet/blob/02afdff08829667ad7411e87b9dfa797809243a0/src/RequestInformation.cs#L187-L210

        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

No one assigned

    Labels

    area-NativeAOT-coreclrin-prThere is an active PR which will close this issue when it is merged

    Type

    No type

    Projects

    Status

    No status

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions