You are previewing Programming F#.

Programming F#

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

Chapter 12. Reflection

We have covered almost all of the raw syntax of F#, and the programming paradigms it enables. In this chapter, you won’t learn any new capabilities of the F# language per se; instead you will learn how to harness the .NET Reflection APIs.

Reflection allows you to access the runtime metadata information about executing code. Metadata can be raw type information, such as the methods a class has, or it can come in the form of attributes, which are programmer-supplied code annotations.

.NET reflection is most commonly used for metaprogramming, which is writing programs that reason about themselves, or modify themselves, such as those that can load plug-ins to add new functionality at runtime; in other words, they allow other developers to extend your application without their needing to have access to the source code.

But before you can do full-on metaprogramming, you must first understand how to annotate code to provide metadata.


Attributes are a form of metadata you can attach to assemblies, methods, parameters, and so on. These annotations can then be inspected at runtime using reflection, which we will get to later in this chapter. The F# compiler will recognize attributes as well; in fact, you have been using attributes for a while now to provide hints for how to compile your code.

Recall from Chapter 5 that in order to mark a class as abstract, you need to provide the [<Abstract>] attribute to the type declaration. When the F# compiler sees that attribute ...

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