Skip to content

System.Reflection.GetCustomAttribute(Type) returns null on .Net5  #61661

@michael-gabbay

Description

@michael-gabbay

Description

I have a code that loads an assembly and using custom attributes to categorize data.

I'm trying to get the actual CustomAttribute object for some interfaces which have the requested Attribute.
on net framework48, the code returns the Attribute value as expected.
during migration to .Net5 - Running the code on .Net5 returns null.
I tried few overloads with no luck.

Reproduction Steps

A custom attribute:

[AttributeUsage(AttributeTargets.Interface)]
public class ApiInterfaceDescriptorAttribute : Attribute
{
    public string ApiUsageName { get; }

    public ApiInterfaceDescriptorAttribute(string apiUsageName)
    {
        ApiUsageName = apiUsageName;
    }
}

Sample interface:

[ApiInterfaceDescriptor("powercontrol")]
public interface IMyInterface 
{
   [ApiMethodDescriptor(ApiExposureLevel.Basic, "a-method...")]
    void SomeMethod();
}

usage:

public void GetApi()
{
   var assembly = Assembly.LoadFile("MyFile");
   var myInterface = assembly.DefinedTypes.FirstOrDefault(...) // get the interface
   var att = myInterface.GetCustomAttribute(typeof(ApiInterfaceDescriptorAttribute));// returns null on Net5 and value on net48
   var att = myInterface.GetCustomAttribute<ApiInterfaceDescriptorAttribute>();// returns null on Net5
}

Expected behavior

return the requested attribute

Actual behavior

method returns null

Regression?

No response

Known Workarounds

Read the CustomAtrributes object[] and itterate and query the requested attribute

Configuration

Running on Win10 x64, .Net5

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.ReflectionquestionAnswer questions and provide assistance, not an issue with source code or documentation.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions