Information Technology Reference
In-Depth Information
Yo u c a n u s e a n y p r o j e c t i o n y o u n e e d t o 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 c o n -
tains all the necessary properties for your dynamic method. As long as you
have properties named “Price” and “Name”, the WritePricingInformation
method will do the job.
Of course, you can use anonymous types that have other properties as well.
As long as the properties you have include the pricing information, you're
fine:
var orderInfo = from n in Ordered
select new {
n.Name,
Price = n.Cost * 1.15M ,
ShippingCost = n.Cost / 10M
};
Plain old C# objects can be used where dynamic is expected. This means
your pricing information method can be used with this concrete type that
happens to use the correct property names:
public class DiscountProduct
{
public static int NumberInInventory { get ; set ; }
public double Price { get ; set ; }
public string Name { get ; set ; }
public string ReasonForDiscount { get ; set ; }
// other methods elided
}
Yo u m a y h a v e n o t i c e d t h a t t h e t y p e o f t h e P r i c e p r o p e r t y i n D i s c o u n t P r o d u c t
is double where the type of the Price property in the earlier anonymous
types was decimal. That's fine as well. WritePricingInformation uses the
dynamic static type, so it will figure that out correctly at runtime. Of
course, if DiscountProduct derived from a base Product class, and the
Product class contained the Name and Price properties, that would work.
The code written above could easily lead you to believe that I'm advocat-
ing dynamic more often than I really am. Dynamic invocation is a good
way to solve this problem, but don't overuse it. Dynamic invocation means
 
Search WWH ::




Custom Search