3

I want to load all Forms that implement the interface IFormLoadSubscriber.

Interface

Namespace Interfaces
    Public Interface IFormLoadSubscriber

    End Interface
End Namespace

At this time it doesn't add anything, subscribing to it is enough.

Form

Namespace Forms
    Public Class MainForm
        Inherits Base.Base
        Implements IFormLoadSubscriber

    End Class
End Namespace

That Base.Base is a form that enforces base behavior.

What I have

Private Shared Function GetSubscribers() As List(Of Type)
    Dim type = GetType(IFormLoadSubscriber)
    Dim subscribers = AppDomain.CurrentDomain.GetAssemblies() _
                      .Where(Function(x) type.IsAssignableFrom(type)) _
                      .Select(Function(x) x.GetTypes())

    Return subscribers
End Function

The problem

The above code does not work as expected, because it returns a large list of lists, containing all sorts of types. If mine is included, it's impossible to find manually. At any rate, this is not what I need.

The question

How do I change the above code so that it returns only one class (as only one class implements IFormLoadSubscriber), in this case my MainForm?

Spikee
  • 3,967
  • 7
  • 35
  • 68
  • 2
    Look at this part: `type.IsAssignableFrom(type)` – sloth Feb 04 '16 at 08:43
  • Well spotted, that doesn't seem right ... how would I fix that? I suppose I would need something like `.Where(Function(x) x.GetType().IsAssignableFrom(type))` but that doesn't return anything. – Spikee Feb 04 '16 at 08:45

2 Answers2

5

Try changing it to

Private Shared Function GetSubscribers() As List(Of Type)
    Dim type = GetType(IFormLoadSubscriber)
    Dim subscribers = AppDomain.CurrentDomain.GetAssemblies() _
                      .SelectMany(Function(x) x.GetTypes()) _
                      .Where(Function(x) type.IsAssignableFrom(x))

    Return subscribers
End Function

Getting all types that implement an interface

Community
  • 1
  • 1
Alex Isayenko
  • 679
  • 8
  • 7
  • That works! But, a minor note, if I don't add `.Where(Function(x) x IsNot type)` it also returns `IFormLoadSubscriber`, which is not what I want (that would cause errors) and it's quite unexpected, as `IFormLoadSubscriber` does not implement itself obviously... – Spikee Feb 04 '16 at 08:57
2

SelectMany will flatten than list of lists.

Dim subscribers = AppDomain.CurrentDomain.GetAssemblies() _
                      .SelectMany(Function(x) x.GetTypes() _
                                  .Where(Function(y) type.IsAssignableFrom(y)))

I have also moved the Where clause inside the SelectMany.

Your where clause is also incorrect, type.IsAssignableFrom(type) is always going to be true.

weston
  • 54,145
  • 21
  • 145
  • 203