Question Enumerate the classes from my interface

punto13

New member
Joined
Apr 22, 2010
Messages
3
Programming Experience
10+
Hi,

I think my problem is easy to solve.

I developed an interface called "Animal".
My programmers created classes for "Dog", "Cat", and "Horse"

Later I want to let the user create an animal in a Windows form. How can I get my annimals to appear in the combo for selecting one of them?

Each animal has it's own DLL. If tomorrow a new animal is developed, the combo should present the new value.

Thank you!
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,583
Location
Norway
Programming Experience
10+
I think my problem is easy to solve.
You're right, but I wonder why you think that and still ask the question? :D The .Net functionality for this is called reflection and is about discovery of the type system.

Since later created libraries can't be referenced now you have to load them dynamically. This sample dynamically loads all assemblies (dll) put in a 'addins' folder:
VB.NET:
For Each dll In IO.Directory.GetFiles("addins", "*.dll")
    Assembly.LoadFrom(dll)
Next
With reflection you can list all types in an assembly, and you can list all assemblies in the domain. The types can be discovered, for example to find out if a class implements a specific interface. This sample gets all classes that implement the IAnimal interface from all assemblies loaded in domain, and lists them in a ComboBox:
VB.NET:
Dim addins = From asm In AppDomain.CurrentDomain.GetAssemblies _
             From t In asm.GetTypes _
             Where t.IsClass AndAlso GetType(IAnimal).IsAssignableFrom(t) _
             Select t

Me.ComboBox1.DisplayMember = "Name"
Me.ComboBox1.DataSource = addins.ToList

And finally this sample gets the selected addin type from combobox and creates an instance, then makes a call (let's say the IAnimal interface has a Eat method):
VB.NET:
Dim animal As IAnimal = CType(Activator.CreateInstance(CType(Me.ComboBox1.SelectedItem, Type)), IAnimal)
animal.Eat()
Btw, one of the news in .Net 4 is Managed Extensibility Framework which addresses the plugin model. Something you may want to look into also.
 
Top Bottom