Skip to content

Generic attributes: Attribute.GetCustomAttributes returns null when passed an unbound generic type #64335

@canton7

Description

@canton7

Description

Attribute.GetCustomAttributes normally returns an empty array when no attributes are found (or throws an exception if the parameters don't make sense).

However, Attribute.GetCustomAttributes(someType, typeof(SomeGenericAttribute<>)) returns null. This is unexpected, particularly as the nullable annotations say that it doesn't return null.

It's worth noting that this wasn't previously possible: it was simply not possible to create a generic type which derived from Attribute, and if you passed a type which wasn't derived from Attribute to Attribute.GetCustomAttributes, you got an exception telling you that. So I suspect this is an unhandled case which just fell through the cracks.

Reproduction Steps

Test.M();

public class Test
{
    public static void M()
    {
        var attrs = Attribute.GetCustomAttributes(typeof(Test), typeof(TestAttribute<>));
        Console.WriteLine(attrs == null); // true
    }
}

public class TestAttribute<T> : Attribute { }

SharpLab

Expected behavior

Attribute.GetCustomAttributes either returns an array, or throws an exception. It should not return null.

Actual behavior

Attribute.GetCustomAttributes returns null in this case.

Regression?

No. It was not previously possible to pass an unbound generic attribute type to Attribute.GetCustomAttributes.

Known Workarounds

No response

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions