I’m trying to create extension method that checks if specific object has specific attribute.
I’ve found example that checks it with the following syntax:
private static bool IsMemberTested(MemberInfo member)
{
foreach (object attribute in member.GetCustomAttributes(true))
{
if (attribute is IsTestedAttribute)
{
return true;
}
}
return false;
}
Now I’m trying to do the following:
public static bool HasAttribute<T>(this T instance, Type attribute)
{
return typeof(T).GetCustomAttributes(true).Any(x => x is attribute);
}
However I get the message ‘The type or namespace ‘attribute’ is missing…’
What am I doing wrong and different from given example / how can I make this happen?
EDIT:
Thanks for the tips, I’ve managed to do it like this now:
public static bool HasAttribute<T>(this T instance, Type attribute)
{
return typeof(T).GetCustomAttributes(attribute, true).Any();
}
And checking for attribute goes like this:
var cc = new CustomClass();
var nullable = cc.HasAttribute(typeof(NullableAttribute));
Thanks for help guys. Now I have another question. Say I want to decorate a property of the class, property of type string, with an attribute, and want to check later on if that property has an attribute. Since this works only with types, I can’t apply it on property level. Is there any solution to property check?
You can’t use a
Typevariable as the argument of anisoperator. Moreover, there’s no need to useAnyto filter this yourself, since there’s an overload ofGetCustomAttributesthat will do it for you.I’ve written this extension method for similar functionality (mine is to return the single attribute appllied to a class):
You could modify this to return a boolean value
a != nullinstead to get what you’re looking for.