Stupid Dynamic Tricks

Yesterday I started working on a new plug-in model for Comicster, such that a plug-in "tool" could appear as a new menu item under the "Tools" menu. You can read more about the results here.

When I first wrote the ITool interface, I gave it a method like this:

void Execute(Item selectedItem);

So when the tool was executed, the only thing it had access to was the currently active item in the main window.

I soon realised that my plug-in was updating the open collection and would need some way to tell Comicster that the file had been modified, so that the user would be prompted to save when they exited the app. Hoping to get something working without having to change the method signature, I struck upon an idea.

As the author of the application, I knew that the main window had a ViewModel behind it with a Content property. I knew that if there was a collection open, that property would be set to an instance of CollectionViewModel, which in turn has an IsModified property. So I wrote some nasty code:

dynamic vm = Application.Current.MainWindow.DataContext;
vm.Content.IsModified = true;

Can you see what it's doing? Because I'm getting hold of the main window's DataContext as a dynamic object, I'm able to do a runtime lookup of the properties without knowing the type! It actually worked a treat!

I don't recommend this, and I've since refactored the plug-in architecture so that plug-ins get passed an IToolContext instance that has the properties they need, but I did think that this was an interesting use for the dynamic feature of C# 4.

c# dynamic comicster .net wpf
Posted by: Matt Hamilton
Last revised: 16 Jul, 2024 07:44 PM History



03 Jun, 2011 01:23 AM @ version 2

I prefer the dynamic solution. Just because the interface is kinder to 3rd party developers, more discoverable, more robust, all-round 'better' in your API; that doesn't make it cooler...

Where are your priorities, Mr Hamilton?

03 Jun, 2011 01:30 AM @ version 2

Maybe I should change it so you just get passed a single parameter like this:

void Execute(dynamic arg);

Now it's up to you to decide what properties you may or may not have access to! Remember to use try/catch blocks liberally! :)

No new comments are allowed on this post.