Inside F#

Brian's thoughts on F# and .NET

Attributes in F#

Posted by Brian on March 24, 2008

One request I’ve had is to show F# code that uses attributes.  Rather than do anything too elaborate, I’ve just written a short, meaningless progress that will let me demonstrate using attributes in F# as well as a couple other noteworthy things.  Here’s the code:

namespace Example

open System
open System.Reflection
open System.Diagnostics

type D =
    | A of int
    | B of string * bool
    member this.DisplayMe() =
        sprintf "%A" this
    //override this.ToString() =
    //    sprintf "%A" this

module MainMod =
    let Main() =
        let x = A(3)
        let y = B("cool", true)
        printfn "Hello" 
        Console.ReadKey() |> ignore    
    [<assembly: AssemblyVersion("")>]

Attributes work much as they do in C# – the main difference is that they are contained in paired brackets like this: [<Attr>].  In the code above, I use the DebuggerDisplay attribute on the discriminated union type "D" so that runtime values of this type display better in the debugger "locals" window.  This F# code also suggestively shows that discriminated union types get compiled into classes, which means they can have member functions (like DisplayMe) just like ordinary classes.  (An alternative way to get a "pretty" experience for values of a particular type in the debugger is to override ToString for that type, as suggested by the commented-out portion of the code.)

Assembly-scoped attributes can only appear in a limited number of places.  One such location is the main "do" block of a module.  In this example, I use the AssemblyVersion attribute to try to provide metadata about the assembly.  Right now the F# compiler fails to respect this attribute, but that is just a bug.  (If you really need to specify the assembly version, you can do so by passing a flag to the compiler, e.g. "fsc –version foo.fs")

That’s all for now!  Hopefully next time I’ll go back to writing about solving interesting problems with F#, but sometimes it’s useful just to take a moment to show off some syntax details.


One Response to “Attributes in F#”

  1. Scott said

    Thanks, Brian!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: