LINQ with Reflection Part 2
I've taken the code in my last post to the next level!
As you recall, I have two interfaces (ICollectionReader and ICollectionWriter) and I have some code (with a very funky LINQ query) to find all the classes in an assembly that implement one of those interfaces and return me a list of instances of them.
I found this evening that this code was almost, but not quite, identical for readers and writers, so I managed to construct a generic method that encompasses both! Here's the method:
private static IEnumerable<T> InstancesOf<T>() where T : class { var type = typeof(T); return from t in type.Assembly.GetExportedTypes() where t.IsClass && type.IsAssignableFrom(t) && t.GetConstructor(new Type[0]) != null select (T)Activator.CreateInstance(t); }
So this method is very similar to the query from my previous post, but it works generically so I can call it for either interface! Now I have this code in my main form's constructor:
CollectionReaders = InstancesOf<ICollectionReader>().ToList(); CollectionWriters = InstancesOf<ICollectionWriter>().ToList();
How clean is that? That pre-populates two properties with all the available classes that implement ICollectionReader and ICollectionWriter respectively! Easy to read and (as an added bonus) a step towards the inevitable MEF implementation!