tags:

views:

72

answers:

3

Can someone please give me an example of using Attribute.isDefined() to check if a particular custom attribute has been applied to a given class?

I've checked msdn, but only see possiblities for attributes applied to assemblies, members etc. I'm also open to alternative methods for achieving the same thing!

+2  A: 
SLaks
Thanks. I wonder why there isn't an overload? I wish working with attributes was a bit cleaner. It's tempting to use marker interfaces and (SomeClass is SomeMarkerInterface).
UpTheCreek
There *is* an overload, IsDefined(MemberInfo, Type) gets the job done. Surprised the heck out of me too :)
Hans Passant
+1  A: 

A simple example:

using System;
using System.Diagnostics;

[Foo]
class Program {
    static void Main(string[] args) {
        var t = typeof(Program);
        var ok = Attribute.IsDefined(typeof(Program), typeof(FooAttribute));
        Debug.Assert(ok);
    }
}

class FooAttribute : Attribute { }
Hans Passant
That's checking a member - what about an attribute on a class? Perhaps the same works?
UpTheCreek
It is *very* unintuitive, the Type class inherits MemberInfo. So the IsDefined(MemberInfo, Type) overload gets the job done. Code snippet updated.
Hans Passant
Ah I see, thanks!
UpTheCreek
A: 

The Type class inherits MemberInfo.
Therefore, you can use the overload that takes a MemberInfo:

if (Attribute.IsDefined(typeof(SomeClass), typeof(SomeAttribute))
SLaks
Ah, thanks that's nicer on the eyes than involving length :)
UpTheCreek