O'Reilly logo

Professional F# 2.0 by Richard Minerich, Talbott Crowell, Aaron C. Erickson, Ted Neward

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

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