Home > C#, Tips And Tricks, WCF > The case for C#’s dynamic keyword

The case for C#’s dynamic keyword

February 22nd, 2011 Nizar Leave a comment Go to comments

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!

Kick It on DotNetKicks.com Shout it
  1. August 15th, 2011 at 08:55 | #1

    Try this typed way.
    private void AddMyEndpointBahavior(ClientBase client) where T :class
    {
    client.Endpoint.Behaviors.Add(new MyEndpointBehavior());
    }

    Joymon

  2. September 22nd, 2011 at 08:03 | #2

    @Joy Oh I needed the argument to be a interface so I can mock for unit-testing purposes.

  1. February 22nd, 2011 at 21:05 | #1