Chapter 12. Custom Attributes

WHAT'S IN THIS CHAPTER?

  • Understanding attribute syntax in F#

  • Defining new custom attributes

  • Applying custom attributes

Custom attributes form a core part of the .NET platform, and as a fully fledged, card-carrying member of the Microsoft family of languages, F# uses and supports custom attributes just as easily and as much as C# or Visual Basic do.

USING CUSTOM ATTRIBUTES

F#, like most .NET languages, uses a variety of BCL-defined attributes to help describe how code should be compiled and consumed not only by other programs written in F#, but also by other .NET programs written in other .NET languages.

Like custom attributes defined in other languages, a custom attribute can appear just about anywhere F# defines a linguistic atom, so custom attributes can appear (among other places) on fields, method, or types, in a manner highly reminiscent of the C# and Visual Basic custom attribute syntax combined, using both square brackets and angle brackets:

open System

[<Serializable>]
type Person(FirstName : string, LastName : string, Age : int) =
    override p.ToString() =
        String.Format("[Person: {0} {1} {2}",
            FirstName, LastName, Age)

As could probably be inferred, this defines a class, Person, that has the BCL-defined Serializable attribute annotated on it, indicating that this class can be serialized using the standard BCL serialization classes and methods.

If the attribute defines or requires additional information (such as the optional message to be displayed when ...

Get Professional F# 2.0 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.