Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where did Attribute.IsDefined go in DNX Core 5.0?

I'm trying to check if a property has an attribute. This used to be done with:

Attribute.IsDefined(propertyInfo, typeof(AttributeClass));

However I get a warning that it's not available in DNX Core 5.0 (it still is in DNX 4.5.1).

Has it not been implemented yet or has it moved like other type/reflection related stuff?

I'm using beta7.

like image 374
SaphuA Avatar asked Sep 30 '15 08:09

SaphuA


1 Answers

Edit:
There actually seems to be an IsDefined extension method in the System.Reflection.Extensions package. Usage:

var defined = propertyInfo.IsDefined(typeof(AttributeClass));

You need to include the System.Reflection namespace. The reference source code can be found here. Beside MemberInfo, it works on Assembly, Module and ParameterInfo too.

This is possibly faster than using GetCustomAttribute.


Original post:

Looks like it's not ported to .NET Core yet. In the mean while you can use GetCustomAttribute to determine whether an attribute is set on a property:

bool defined = propertyInfo.GetCustomAttribute(typeof(AttributeClass)) != null;

You could bake this into an extension method:

public static class MemberInfoExtensions
{
    public static bool IsAttributeDefined<TAttribute>(this MemberInfo memberInfo)
    {
        return memberInfo.IsAttributeDefined(typeof(TAttribute));
    }

    public static bool IsAttributeDefined(this MemberInfo memberInfo, Type attributeType)
    {
        return memberInfo.GetCustomAttribute(attributeType) != null;
    }
}

And use it like this:

bool defined = propertyInfo.IsAttributeDefined<AttributeClass>();
like image 132
Henk Mollema Avatar answered Oct 08 '22 00:10

Henk Mollema