Free mag vol1 | Page 489

CHAPTER 11  ADVANCED C# LANGUAGE FEATURES Anonymous Types Containing Anonymous Types It is possible to create an anonymous type that is composed of other anonymous types. For example, assume you want to model a purchase order that consists of a timestamp, a price point, and the automobile purchased. Here is a new (slightly more sophisticated) anonymous type representing such an entity: // Make an anonymous type that is composed of another. var purchaseItem = new { TimeBought = DateTime.Now, ItemBought = new {Color = "Red", Make = "Saab", CurrentSpeed = 55}, Price = 34.000}; ReflectOverAnonymousType(purchaseItem); At this point, you should understand the syntax used to define anonymous types, but you might still be wondering exactly where (and when) to use this new language feature. To be blunt, anonymous type declarations should be used sparingly, typically only when making use of the LINQ technology set (see Chapter 12). You would never want to abandon the use of strongly typed classes/structures simply for the sake of doing so, given anonymous types’ numerous limitations, which include the following: • You don’t control the name of the anonymous type. • Anonymous types always extend System.Object. • The fields and properties of an anonymous type are always read-only. • Anonymous types cannot support events, custom methods, custom operators, or custom overrides. • Anonymous types are always implicitly sealed. • Anonymous types are always created using the default constructor. However, when programming with the LINQ technology set, you will find that in many cases this syntax can be very helpful when you want to quickly model the overall shape of an entity rather than its functionality.  Source Code The AnonymousTypes project can be found under the Chapter 11 subdirectory. Working with Pointer Types And now, the final topic of the chapter, which most likely will be the least-used of all C# features for the vast majority of your .NET projects. 429