Using Dynamic Classes to Pass Data
In an earlier tip on using tuples to return multiple values from a method, several readers noted that the tuple's property names (Item1, Item2) left a lot to be desired -- you couldn't really call those names "self-documenting". As a fan of Really Obvious Code (ROC Rocks!), I should point out that there's a solution: using a Dynamic class. As with tuples, the goal here is to create a way to return multiple values from a method without defining a whole new class with its attendant properties and then using that class in exactly one place (returning values from a method) for just a few milliseconds.
A dynamic class lets you add properties to a class without defining them beforehand, as in this example which defines the variable returnClass as dynamic and then adds a CustomerID and Age property to it just by setting values on those properties:
private dynamic GetCustomerInfo()
returnClass.CustomerID = "A123";
returnClass.Age = 21;
To call this method, accept the class, and access the properties, you'd write code like this:
aClass = GetCustomerInfo();
this.CustIdTextBox.Text = aClass.CustomerID;
What you give up with Dynamic classes is IntelliSense: when accessing the properties on aClass, IntelliSense won't provide the list of property names for the class. However, compared to using tuples (with the distinctly unhelpful names Item1, Item2 and so on), that's not a real loss. What you do lose that you may care about, however, is compile-time type safety: if you set a dynamic property to a string and then attempt to move the value into an integer variable, you won't find about your problem until the code executes at runtime.
As another reader pointed out in that original column, neither technique is a good choice for a public interface, but worth considering when you have two private methods interacting.
Posted by Peter Vogel on 02/13/2012 at 6:47 AM