Click here to Skip to main content
15,896,442 members
Articles / Programming Languages / C#

The Case for C#’s Dynamic Keyword

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
12 Mar 2012CPOL 6.6K   3   2
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:

C#
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):

C#
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!

This article was originally posted at http://nizarnoorani.com/index.php/archives/267

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) NCube, Inc.
United States United States
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.

Comments and Discussions

 
QuestionSuggestion Pin
Jeff.Crawford12-Mar-12 5:45
Jeff.Crawford12-Mar-12 5:45 
AnswerRe: Suggestion Pin
Nizar Noorani16-Mar-12 3:50
Nizar Noorani16-Mar-12 3:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.