Hi,
F# uses more general approach to "extension members" than C#, but it is genreally based on the similar idea of "adding" some members to a type. Of course there are some (very reasonale) limtations such as that these extension members can't access private state of the object or can't add new fields to store the state.

In F# this can be written using a "type augmentation" which looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
#light
open System

// This is the type augmentation
type System.Random with 
  // Adding a new method...
  member r.NextDice() =
    (r.Next  + 1)
  // and a new property (with getter only)
  member r.DiceValue
    with get() = r.NextDice()
  
let rnd = new Random()

Console.WriteLine("Dice: {0}", rnd.NextDice())
Console.WriteLine("Dice: {0}", rnd.DiceValue)
Console.ReadLine()

The type augmentation looks like an ordinary type declaration, but it uses the "with" keyword and the name has to be specified using the full namespace name (which of course has to be an existing type).

By on 7/31/2007 4:11 PM ()

Excellent, Thomas! That's exactly what I was looking for. :)

--Ray V.

By on 7/31/2007 5:10 PM ()

Hi Ray,

Just to add that as of 1.9.2.7 this feature is a little "under cooked". The syntax above won't change, but there are a few restrictions that apply. Here are some additional rules:

  • Extension member declarations must be in modules. Putting them in namespaces will give strange errors later in the day. Current F# practice is to put the extension members in a module called A.B.C.CommonExtensions.
  • You must open that module to bring the extension members into scope

Here is a current design limitations:

  • There is currently no "fully qualified" way of calling the extension member
  • We don't yet recognize C# extension members (e.g. the LINQ query operators)

Here are the known bugs:

  • The feature has only been extensively tested for record/union/class types.
  • Defining extension members for interface types is NYI.
  • Adding extension methods in F# interactive doesn't work well. Essentially if you add the same extension twice you'll subsequently get lots of conflicts on later lookups. This is fairly hard to fix so we may not be fixing it at all.

Regards

don

By on 7/31/2007 6:30 PM ()

Thanks, Don! That's very helpful. Extension members are still a very useful and welcome addition to the language.

By on 8/1/2007 6:49 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper