Earlier this week, I ran into an issue while using the dynamic keyword in C#. I learned from C# in Depth that there are a couple of restrictions with dynamic, most notably when using extension methods or converting lambda expressions. But apparently there are more restrictions than meets the eye, which came as an unpleasant surprise. Let’s look at some code.
Here we have an interface called IPresenter with a single method on it named Start. Notice that the Start method has a single parameter which is defined as dynamic. We also have another interface called ISpecificPresenter that inherits from IPresenter. Finally we have a concrete class that implements the ISpecificPresenter interface. So far, so good.
Next we have a class called Activator that we use to kick-off a particular presenter.
The Activator class has a generic Start method with a parameter named startupData that is also dynamic. Here we simply get an instance of a requested presenter from StructureMap and call its Start method. This is how to call the Start method of the Activator class :
When we run this code, we get the following exception:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'ISpecificPresenter' does not contain a definition for 'Start'.
This had me stumped for a while until I added a cast from ISpecificPresenter to IPresenter in the Start method of the Activator class.
public interface IPresenter
{
void Start(dynamic startupData);
}
public interface ISpecificPresenter : IPresenter
{}
public class SpecificPresenter : ISpecificPresenter
{
public void Start(dynamic startupData)
{
// ...
}
}
Now everything works as expected. But I’m not entirely sure why this isn’t behaving as I expected. I guess it has something to do with the fact that the Start method is defined on the IPresenter interface and not on the ISpecificPresenter interface.
Although I very much like the flexibility that dynamic objects bring to the C# language, I’m also starting to think that it might not be such a good idea to bring dynamic concepts to a statically typed language. Running into these kind of issues and limitations reinforces this growing opinion.
I would much appreciate it if anyone could enlighten me with a good explanation.
Until next time.