views:

141

answers:

3

In a project of mine I'm currently doing this:

    addTemplateToList(New docNULL)
    addTemplateToList(New docAgenda)
    addTemplateToList(New docAgendaNew)
    addTemplateToList(New docOffer)
    :
      20 more
    :
    addTemplateToList(New docRequest)

all classes inherit docMain and addTemplateToList( X ) adds x to a List(Of docMain).

Now my question is: Is there a better way to do what's done in the code sample?

I thought of something like:

for all x as docMain in ALLAVAILABLECLASSES
  if x.className().beginswith("doc") then addTemplateToList(x)
next

Is this somehow possible in VB.net (Reflection?)?

A: 

Google vb.net reflection gives:

http://www.vbdotnetheaven.com/UploadFile/rahul4_saxena/Reflection09122007031247AM/Reflection.aspx

Do note that although it will make your code more flexible/ shorter. This is not optimization, reflection is a generally expensive feature in programs.

Thirler
A: 

You need to use reflection, even better use MEF ( http://www.codeplex.com/MEF ) so you can stick new modules on runtime or just by dropping a DLL.

As someone said before it won't make it faster yet less code more flexibility.

dr. evil
+1  A: 

I've found a quite simple solution to my problem:

    Dim m As Type = Type.GetType("mainARGQ.docCreator")
    For Each TypeObj As Type In [Assembly].GetExecutingAssembly().GetTypes()
        If TypeObj.BaseType Is m And TypeObj IsNot m Then
            addTemplateToList(Activator.CreateInstance(TypeObj))
        End If
    Next

Edit: Just wondering if there's a way to simplify "TypeObj.BaseType Is m And TypeObj IsNot m"

Chris
A class base type is never itself, so you can get rid of the And part.
Wilhelm