Reputation: 3150
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.
Upvotes: 8
Views: 1921
Reputation: 46591
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
.
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>();
Upvotes: 11