Reputation: 16959
Is there an equivalent of typeof( )
for a custom attribute?
Specifically I would like to rewrite this code in such a way where I wouldn't rely on string comparison
if (prop.GetCustomAttributes(true).Any(c => c.GetType().Name == "JsonIgnoreAttribute")) { ... }
Upvotes: 0
Views: 1537
Reputation: 51330
There is an overload of GetCustomAttributes
which takes the type you want as a parameter:
prop.GetCustomAttributes(typeof(JsonIgnoreAttribute), true)
But as you're actually checking for the presence of the attribute, you should rather use the IsDefined
function:
if (Attribute.IsDefined(prop, typeof(JsonIgnoreAttribute), true))
This does not instantiate the attributes, and is therefore more performant.
If you didn't need the inherit parameter, you could have written:
if (prop.IsDefined(typeof(JsonIgnoreAttribute)))
For some reason, this parameter is ignored in the MemberInfo.IsDefined
function of properties and events, but taken into account in Attribute.IsDefined
. Go figure.
Note that any type assignable to JsonIgnoreAttribute
will be matched by these functions, so derived types will also be returned.
As a side note, you could have directly compared the Type
objects like this:
c.GetType() == typeof(JsonIgnoreAttribute)
(is it the exact same type?),
or c is JsonIgnoreAttribute
(is the type assignable?).
Upvotes: 3
Reputation: 101690
What's wrong with using typeof()
? or better yet, is
?
if (prop.GetCustomAttributes(true).Any(c => c is JsonIgnoreAttribute))
You could also do:
if (prop.GetCustomAttributes(true).OfType<JsonIgnoreAttribute>().Any())
or
if (prop.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any())
Upvotes: 2