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

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