You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.
O'Reilly logo

Using Reflection

So now that you know all about reflection, what do you do with it? In other words, what is metaprogramming?

Next, we will look at two specific applications of .NET reflection: declarative programming and writing plug-in systems.

Declarative Programming

Perhaps the simplest thing to do when using reflection is to create more declarative code. Rather than hardcoding data into properties and methods, you can encode data by using attributes instead. This leads to potentially cleaner and more readable code.

Consider Example 12-8, which defines a function determineBoxToUse to calculate the proper container to ship an item in. Each item that can be shipped inherits from the ShippingItem class and overrides the Weight and Dimension properties, which are used to determine the correct box size.

No reflection or declarative programming is used just yet; we’ll see how we can improve upon this code next.

Example 12-8. Simple shipping software

/// Pounds
[<Measure>]
type lb

[<Measure>]
type inches

type Container =
    | Envelope
    | Box
    | Crate

type Dimensions =
    { Length : float<inches>; Width : float<inches>; Height : float<inches> }

[<AbstractClass>]
type ShippingItem() = abstract Weight : float<lb> abstract Dimension : Dimensions // Piece of paper describing what is in the box type ShippingManifest() = inherit ShippingItem() override this.Weight = 0.01<lb> override this.Dimension = { Length = 11.0<inches> Width = 8.5<inches> Height = 0.01<inches> } // Will it blend? type Blender() = inherit ...

The best content for your career. Discover unlimited learning on demand for around $1/day.