Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

The Case for C#’s Dynamic Keyword

0.00/5 (No votes)
12 Mar 2012 1  
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!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here