Information Technology Reference
In-Depth Information
Generic methods could only assume the functionality defined in
System.Object. System.Object held the same limitations. Of course, at
some point, you'll find that you really need a named class with actual
behavior. This item discusses what to do when you want to work with dif-
ferent anonymous types that may have properties of the same name but
aren't part of your core application and don't warrant the work to create
a new named type.
The static type of dynamic enables you to overcome this limitation.
Dynamic enables runtime binding and instructs the compiler to generate
all the necessary code to work with whatever the runtime type may be.
Suppose you needed to print information for a price list. Further suppose
that your price list may be generated from multiple data sources. You may
have one database for items in inventory, another for items that are special
order, and yet another for items sold through a third-party supplier.
Because these are completely different systems, they may all have different
abstractions for the product. Those different abstractions may not have
the same names for their properties, and they certainly won't have the same
base class or implement the same interface. The classic answer is to imple-
ment an adapter pattern (see Design Patterns , Gamma, Helm, Johnson, &
Vlissides, pp. 139-142) for each of the product abstractions, and convert
each object to a single type. That's quite a bit work, and you have more work
to do every time a new product abstraction is added. However, the adapter
pattern stays in the static type system and will have better performance.
Another, lighter-weight solution is to use dynamic to create a method that
works with any type that has the pricing information you seek:
public static void WritePricingInformation( dynamic product)
{
Console .WriteLine( "The price of one {0} is {1}" ,
product.Name, product.Price);
}
Yo u c a n c r e a t e a n a n o n y m o u s t y p e t h a t m a t c h e s t h e p r o p e r t i e s y o u c h o s e
for your pricing method anywhere in your code where you pull informa-
tion from one of your data sources:
var price = from n in Inventory
where n.Cost > 20
select new { n.Name, Price = n.Cost * 1.15M };
 
Search WWH ::




Custom Search