views:

48

answers:

2

Hello SO;

I have an issue with .Net reflection. The concept is fairly new to me and I'm exploring it with some test cases to see what works and what doesn't. I'm constructing an example wherein I populate a set of menus dynamically by scanning through my Types' attributes.

Basically, I want to find every type in my main namespace that declares 'SomeAttribute' (doesn't matter what it is, it doesn't have any members at present). What I've done is:

    For Each itemtype As Type In Reflection.Assembly.GetExecutingAssembly().GetTypes
        If itemtype.IsDefined(Type.GetType("SomeAttribute"), False) Then
            'do something with the type
        End If
    Next

This crashes the application on startup - the first type it identifies is MyApplication which is fairly obviously not what I want. Is there a right and proper way to look for all the 'real' 'sensible' types - i.e. classes that I've defined - within the current assembly?

+1  A: 

How about a little Linq

var list =  AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).
                        Where(x => x.GetCustomAttributes(typeof(MyAttribute), false).Length > 0);
astander
+1  A: 

It is most likely that IsDefined() fails since Type.GetType("SomeAttribute") returns null. Try adding the namespace to the attribute name:

Type.GetType("SomeNamespace.SomeAttribute")
Elisha
Thanks, the cause is blindingly obvious. Thanks to all the other responders as it's all useful information, this one is *technically* the answer however - the root cause was my own carelessness.
Tom W