65.9K
CodeProject is changing. Read more.
Home

The Case for C#’s Dynamic Keyword

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Mar 12, 2012

CPOL
viewsIcon

6845

In the post, I share a scenario which required the use of the 'dynamic' keyword.

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());
}
/* Note that the method is taking in an object to type 
    'System.ServiceModel.ICommunicationObject' which is the base-level 
    interface for all WCF client proxies.
*/

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!