Tuesday, January 23, 2007

When iterating attributes, make sure you get the right thing

I'll admit I kind of dubbed out on this one. When you're trying to get the custom attributes off of an object, make sure you're getting the right object. In my case, I needed to get the Attributes of my assembly, not the Assembly class itself.

It should come as no surprise that the following code doesn't do what I expected:



object[] attribs = Assembly.GetExecutingAssembly().GetType().GetCustomAttributes(typeof(Attribute), false);



Instead I just needed to remove the call to GetType():



object[] attribs = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(Attribute), false);



The Assembly class provides a handy GetCustomAttributes() method since calling it on the Assembly type itself doesn't really help you much. The first example gets you a bunch of crazy attributes that really aren't what I was looking for; the second returns all of the assembly-decorating attributes declared in my AssemblyInfo.cs.

No comments: