C
C#2y ago
Hugh

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:
foreach(var customAttr in method.CustomAttributes)
{
if(customAttr.AttributeType is MyAttribute)
foreach(var customAttr in method.CustomAttributes)
{
if(customAttr.AttributeType is MyAttribute)
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
ero
ero2y ago
== typeof(MyAttribute)?
Hugh
HughOP2y ago
Ah - I was thinking that typeof would take an object and return a type Thanks
ero
ero2y ago
that'd be GetType()
Hugh
HughOP2y ago
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()
sunder.cc
sunder.cc2y ago
@Hugh not enterily sure what youre exactly doing but the Type class has a GetCustomAttribute method which you can use like this:
method.GetType().GetCustomAttribute<MyAttribute>();
method.GetType().GetCustomAttribute<MyAttribute>();
Hugh
HughOP2y ago
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
Want results from more Discord servers?
Add your server