O'Reilly logo

Programming F# by Chris Smith

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required