Comparing types when using reflection
I'm using the reflection system, and want to check the type of an attribute (this may not be relevant here, but I wanted to give some context)
I'm iterating over method custom attributes, and want to check if one of them is a specific type (
MyAttribute
)
I thought I'd be able to do this:
However, it never hits this, and VSCode underlines it in yellow saying The given expression is never of the provided ('MyAttribute') type
How do I check a type against another type? Google is only helping me with checking an object against a type.6 Replies
== typeof(MyAttribute)
?Ah - I was thinking that
typeof
would take an object and return a type
Thanksthat'd be
GetType()
Thanks - good to know!
A small follow-up to this one...
This works if the type is exactly the same. How would I check if
customAttr.AttributeType
is a subclass of MyAttribute
?
Please ignore - I found IsAssignableFrom()
@Hugh not enterily sure what youre exactly doing but the Type class has a GetCustomAttribute method which you can use like this:
I have a base attribute and I want to find any attributes of subclasses. In the end
typeof(MyAttribute).IsAssignableFrom(customAttr.AttributeType)
worked for me