Found a Reason to use Dynamic in C# 4.0

 I've been asked: "why use dynamic"?  I admit, there aren't a lot of areas where dynamic is really needed.  But there are some, and while I'd recommend limiting use of the dynamic keyword, I would never suggest not to ban it.  One of the uses where I found it handy is with wrapper classes.  I was developing a wrapper that looked like:

public class DataBoundWrapper
{
  private Control _control = null;

  public static DataBoundWrapper Create(GridView control)
  {
      return new DataBoundWrapper(control);
   }

  public static DataBoundWrapper Create(DetailsView control)
  {
      return new DataBoundWrapper(control);
   }
}

I left out the constructor, but basically it takes the control reference and assigns it to _control.  Now, to wrap I would do something like this:

public string DataSourceID
{
   get
   {
      if (_control is GridView)
          return ((GridView)_control).DataSourceID;
      else if (_control is DetailsView)
          return ((DetailsView)_control).DataSourceID;
    }
}

This is because the GridView and DetailsView do not define some of these properties in a base class; they each define the same properties repeatedly.  I personally think this is a limitation of the controls, but the design is what it is.  THe DataSourceID property may not be the best example, but other properties like AutoGenerateColumns (or Fields), paging properties, and many more properties are not defined in a common base class or interface.

So a way around this may be to change the definion to use:

dynamic _control;

And have each property use now instead:

public string DataSourceID
{
  get { return _control.DataSourceID; }
  set { _control.DataSourceID = value; }
}

Now the control's properties are linked dynamically at runtime, and because both controls have a DataSourceID, this works and is a lot easier to implement.

Published Friday, November 21, 2008 9:53 PM by bmains
Filed under:

Comments

No Comments