views:

39

answers:

1

I have something that looks like the following:

[CoolnessFactor]
interface IThing {}

class Tester
{
    static void TestSomeInterfaceStuff<T>()
    {
        var attributes = from attribute 
                        in typeof(T).GetCustomAttributes(typeof(T), true)
                        where attributes == typeof(CoolnessFactorAttribute)
                        select attribute;
        //do some stuff here
    }
}

and then I would call it like so:

TestSomeInterfaceStuff<IThing>();

However, when I do this, it doesn't return any attributes at all.

Thoughts?

+5  A: 

The "in" line needs adjusting. It should read

in typeof(T).GetCustomAttributes(typeof(CoolnessFactorAttribute), true)

The type passed into the GetCustomAttributes method identifies the type of attributes that you are looking for. It also means the following where clause is unnecessary and can be removed.

Once you remove that clause though, it removes the need for the query. The only real improvement that can be done is to cast the result in order to get a strongly typed collection.

var attributes = 
  typeof(T).GetCustomAttributes(typeof(CoolnessFactorAttribute),true)
  .Cast<CoolnessFactorAttribute>();
JaredPar