O'Reilly logo

Programming F# 3.0, 2nd Edition 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

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.

The most common usage of .NET reflection is 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, allowing other developers to extend your application without them 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

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

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