Many developers feel, myself included, that C#’s ‘dynamic
’ keyword is… well, a little too dynamic. But, recently, I faced a challenging problem which I was only able to solve through the use of the ‘dynamic
’ keyword! Here goes…
In short, I had to write a method that adds a WCF behavior to a VS-generated WCF proxy class. What I wanted to do is something like the following:
public void AddCommonWcfBehavior(ICommunicationObject wcfClientProxy)
{
ClientBase wcfClientBase = wcfClientProxy as ClientBase;
wcfClientBase.Endpoint.Behaviors.Add(new MyCommonWcfBehavior());
}
However, I couldn’t do this for the simple reason that ClientBase<>
is a generic class and .NET does not provide a non-generic version. Go figure! And no, for reasons that are too detailed to list here, I could not make AddCommonWcfBehavior()
a generic method. I wish .NET offered a non-generic ClientBase
class. But it doesn’t and thus I was stuck!
It was then that I remembered reading about the dynamic
keyword not too long ago. Using the dynamic
keyword, the method looks like the following (and works as expected):
public void AddCommonWcfBehavior(ICommunicationObject wcfClientProxy)
{
dynamic wcfClientBase = wcfClientProxy;
wcfClientBase.Endpoint.Behaviors.Add(new MyCommonWcfBehavior());
}
So the moral of the story: Keep the dynamic
keyword in mind! In some cases, it may be your one and only savior!
Nizar Noorani is an independent software consultant. He provides services in the areas of web applications and systems architecture, analysis, design and development. Although proficient in a variety of technologies, he specializes in the .NET technology. He can be reached at nizar.noorani@gmail.com.