Using Types in Data-Driven Code

Earlier, in the section entitled "Type, Object, and Component,” we saw how the loading and compilation process of the CLI is data-driven, with many decisions made by examining embedded metadata tokens at the last possible moment. This technique is not limited to the JIT compiler—it can be used by custom programs as well. The use of type information to drive program decisions is called introspection or reflection —the component’s code is reflecting on its own structure and making decisions based on this information.

Programs with sufficient permissions can create, manipulate, and examine type metadata, either from managed code (using the System.Reflection family of types) or from unmanaged code (using the unmanaged APIs described in clr/src/inc/metadata.h that are outside the CLI specification). Type descriptions can be used to defer decisions until runtime, enabling looser linkages between components and more robust load-time adaptations.

This last point deserves a bit more in the way of explanation—specifically, the idea of using component metadata to promote looser coupling between components may be a new concept for many. Consider, for a moment, a desire to take an existing in-memory object instance and save its current state to some secondary storage stream (e.g., the filesystem, or sent as part of an HTTP request, or even to a binary field in a database.) Under formal, object-oriented approaches, this is common behavior across types and therefore ...

Get Shared Source CLI Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.