This is a nice quick one. When creating a class structure that make use of interfaces there may be times that you want to list all of the classes that implement that type. A recent example that I came across was where I'd written some software to interface with an admin system to perform bulk operations taking information from a csv file. Of course, writing a one hit class structure to perform one set of logic based on one input template would be a waste so I used interfaces to describe a standard set of features of the load logic and implemented that interface when writing a new template and set of logic, so far so standard. What I thought would be nice was if on the front end instead of hard coding references to each logic type I could simply grab a list of all the classes that implemented my interface - and this is that snippet.
// set up the loadtype combobox var type = typeof(IDataLoadLogic); var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => type.IsAssignableFrom(p) && !p.IsInterface); Dictionary<string, string> TypeDict = types.ToDictionary(x => x.Name, x => x.AssemblyQualifiedName); LoadTypecomboBox.DataSource = new BindingSource(TypeDict, null); LoadTypecomboBox.DisplayMember = "Key"; LoadTypecomboBox.ValueMember = "Value";
Whilst my implementation meant that I'd separated out the logic the below is essentially how to turn the combobox values back into an instance of the interface that you've selected for. In my case this was perfect and allows for the use of strongly typed methods you could always instantiate your class into a dynamic type object and access all of the methods that you'll know are there (disclaimer: this approach can lead to issues in maintainability and isn't one that I'll personally use through choice).
string AssemblyQualifiedName = LoadTypecomboBox.SelectedValue.ToString(); Type DynaGrab = Type.GetType(AssemblyQualifiedName); IDataLoadLogic LogicInstance = (IDataLoadLogic)Activator.CreateInstance(DynaGrab);
You're now left with an object that you can call any of the interfaced methods on and it will run the implementation of the class that you've selected, lovely!.