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?

2
  • 2
    Look at this part: type.IsAssignableFrom(type) Commented Feb 4, 2016 at 8: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. Commented Feb 4, 2016 at 8:45

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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...
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.